0

I am writing my first bash script to loop through a CSV with old username to new usernames. I only read the new username to make the linux account

while read old_name new_name
do
   new_name="$(tr [A-Z] [a-z] <<< $new_name)"
   echo $new_name
   cmd= useradd -g groupid -s /bin/ksh $new_name >> $LOGFILE 2>&1
   echo password | passwd --stdin $new_name

But some users already exist and don't need a new password. Only the new users need the password.

When a user already exists I get useradd: user 'username' already exists

How can I fix this?

1

1 Answer 1

2

The linked question covers how to determine whether a user already exists but I would suggest making a couple of other modifications to your script:

# always use -r (raw) switch unless you have a specific reason not to
while read -r old_name new_name
do
    new_name=${new_name,,} # convert to lowercase using parameter expansion
    if ! id -u "$new_name" &>/dev/null # check user doesn't exist
    then
        useradd -g groupid -s /bin/ksh "$new_name" &>"$LOGFILE"
        passwd --stdin "$new_name" <<<password # avoid useless echo + pipe
    fi
done

As mentioned in the comments, you may have to resort to your original method to convert $new_user to lowercase if you're using an older version of bash (the ${var,,} syntax is a bash 4 feature). If you use [:upper:] and [:lower:] instead of [A-Z] and [a-z] then your script will be less locale-specific, which may be something to be aware of.

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

2 Comments

Thanks Tom. i will test i tomorrow in my test env.
${new_name,,} requires bash 4, though. Earlier versions will have to use new_name=$(tr [:upper:] [:lower:] <<< "$new_name").

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.