theDrifter theDrifter - 1 year ago 64
Bash Question

Variable in Command in bash script

Hello i want to automate setting up users on my servers. So i started with this simple bash

#! /bin/bash

if [ $# -ne 2 ]
echo "Usage: $(basename $0) USERNAME PASSWORD"
exit 1

exec useradd -m $user_name
usermod -s /bin/bash
#echo "$2" | exec chpasswd $user_name --stdin
usermod -aG www-data "${user_name}"

I have a problem with the last line. The user i just created does not get assigned to the group
. When i use only the last line and comment everthing else and feed my one user into the script i am able to add myself, can someone explain me why this is faling?

Answer Source
exec useradd -m $user_name

substitutes the current process ie bash here with useradd -m $user_name.
Moreover I don't see any practical advantage of using exec here.

Also, as the Linux password can have whitespaces, I suggest doing

password_var="$2" #prevents word splitting

With some error checking, my final script would be

useradd -mp "$password_var" "$user_name"  # You haven't used password 
if [ $? -ne 0 ] # checking the exit status of the last command
  echo "User creation failed"
  exit 1
usermod -s /bin/bash "$user_name"  #username missing in the original code
usermod -aG www-data "$user_name"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download