Reputation: 1
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?
Upvotes: 0
Views: 160
Reputation: 74596
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.
Upvotes: 2