Bash – Proper way to add a user account via bash script

bashshell-scriptuseraddusers

I cross posted this question to AskUbuntu because my problem seems most acute on Debian/Ubuntu, but it was suggested that I ask here. Whatever method is suggested for solving this problem should work on most distros (e.g., openSuse & Ubuntu). 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"

There are several problems with the user account it creates on Ubuntu.

  • 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. But I need a non-Debian-exclusive script or method of adding user accounts via my bash script.

I also had a previous question on this topic, but it was different enough that it is not relevant to this problem.

Best Answer

The problem is that the default shell for a new user on Debian is /bin/sh so most of the features you're used to from bash aren't there. Try adding -s /bin/bash to your useradd command.

You can also change the default shell permanently by editing /etc/default/useradd.

Edit:

The solution to automatically modify the password (as found by MountainX) is here

Related Question