0

I'm trying to modify a script that read usernames/password from a file which is like this:

user1 pass1
user2 pass2
user3 pass3

I can't get the script to read the space between the users and pass. What can I use to delimit this space? This is my code:

for row in `cat $1`
do
  if [ $(id -u) -eq 0 ]; then


      username=${row%:*}
      password=${row#*:}
      #echo $username
      #echo $password

I know I have to change the stuff in ${row%:} and ${row%:}

What do I have to put so it sees the space between user1 pass1 ?

1 Answer 1

3

It would be easier to split the two fields as you read each line. You can do that with read. It's also better to use a while loop here (a for loop requires to play with $IFS and it would also load the entire file in memory):

#!/bin/bash
if [ "$EUID" -ne 0 ]; then
    echo >&2 "You are not root"
    exit 1
fi

while read -r username password; do
    # do the useradd stuff here
done < "$1"

Notice that I also changed $(id -u) to $UID which should be faster since it does not invoke an external program.

Sign up to request clarification or add additional context in comments.

2 Comments

Put it in a file, e.g. myscript.sh (don't forget to add a shebang at the top: #!/bin/bash) and then run it like so ./myscript.sh passwords.txt.
Got it to read the file. Now how would I add this bit of code to my main script so it can create the users? I edited my main script in the question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.