Home > Mobile >  How do I get this to display the shell?
How do I get this to display the shell?

Time:07-28

To get this code to run properly, I created a txt file named new_user.txt with the following format (supposed to follow /etc/passwd)

    doejjan:x:Doe, Jane Joe 111222:home/STUDENTS/teststu:/bin/bash
    smidjoh:x:Smith, John Jay 222333:home/STUDENTS/teststu:/bin/bash

I want to try to display the command that was created to show every record on the screen, below is what I have so far:

#!/bin/bash

while read -r line || [[ -n "$line" ]]; do
  username=$(echo "$line" | cut -d: -f1)
  GECOS=$(echo "$line" | cut -d: -f5)
  homedir=$(echo "$line" | cut -d: -f6)
  echo "adduser -g '$GECOS' -d '$homedir' -s /bin/bash '$username'"
done < "$new_user.txt"

I'm getting the error in line 7 that says the following: .txt:No such file or directory

Can you help me try to fix the error message? Thank you in advance.

CodePudding user response:

From the error message, you can understand that the variable new_user must be empty. Indeed you never assign a value to this variable.

From your description, it follows that $new_user should expand to the value new_user. Say your script is called my_script. If you run it as

new_user=new_user my_script

the error will be gone. If the script is run most of the time on the file new_user.txt, you can - in your script - provide a default value for this variable:

: ${new_user:=new_user}

If you then run it as

my_script

it will pick up new_user.txt, but if you run it by

new_user=old_user my_script

it will run on old_user.txt.

BTW, I personally would prefer passing the file name to the script either via stdin or on the command line, but you have choosen to use a variable for this task, and you can do this of course, if you prefer.

  • Related