Celeb Glow
updates | March 20, 2026

Proper way to add a user account via bash script

Here's the script code I'm using now:

getent group $MYGROUP
if [ $? -ne 0 ] ; then sudo su -c "groupadd $MYGROUP"
fi
sudo su -c "useradd mynewuser -p mypassword -m -g $PRIMARYGRP -G $MYGROUP"

This approach works well on openSuse. But there are several problems with the user account it creates on Ubuntu so I am seeking help here.

  • the terminal prompt isn't set (echo $PS1 returns nothing)
  • the arrow keys and tab key do not work correctly in the terminal
  • the password doesn't seem to work (although I'm still unclear exactly what this issue is)
  • the /etc/sudoers rights set for this new user are not honored

If instead I manually create the user with adduser (instead of useradd) I don't have these problems on Ubuntu. But I can't use adduser on openSuse (afaik). Therefore, I need a non-Debian-exclusive script or method of adding user accounts via my bash script that works on Ubuntu (and doesn't stop working on other distros).

Finally, I would like to understand the differences between adduser and useradd. For example, I want to know which skeleton directory is used by adduser as that might be the reason useradd isn't working as expected (because I just accepted the default).

Thanks

11

4 Answers

My solution was provided here: by Ulrich Schwarz and Joseph R.. The main thing I had to do was add -s /bin/bash to my existing useradd command and remove -p password which expects an encrypted password.

sudo su -c "useradd mynewuser -s /bin/bash -m -g $PRIMARYGRP -G $MYGROUP"

Then do this:

sudo chpasswd << 'END'
mynewuser:password
END
1

This will work.

sudo adduser myuser --gecos "First Last,RoomNumber,WorkPhone,HomePhone" --disabled-password
echo "myuser:password" | sudo chpasswd
0

my script which automatically constructs a service account with ssh key login and no password

#add service group/user
addgroup service-runner
useradd devops-service --create-home --shell /bin/bash --groups service-runner
#gpasswd -a devops-service sudo #allowing sudo requires password, and not a good idea for a service account.
mkdir /home/devops-service/.ssh
chmod 700 /home/devops-service/.ssh
cat >> /home/devops-service/.ssh/authorized_keys
chown devops-service:devops-service /home/devops-service -R
1

I suppose you can simply use a condition in your script, something like

if grep -q 'Ubuntu\|Debian' /etc/issue; then adduser .....
else useradd .....
fi

(cannot verify if the file /etc/issue is present on OpenSUSE, otherwise you can put the condition on the existence of such a file).

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy