theDrifter
theDrifter

Reputation: 1696

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 ]
then
 echo "Usage: $(basename $0) USERNAME PASSWORD"
 exit 1
fi
user_name=$1
password_var=$2

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 www-data. 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?

Upvotes: 0

Views: 556

Answers (1)

sjsam
sjsam

Reputation: 21965

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

password_var="$2"
useradd -mp "$password_var" "$user_name"  # You haven't used password 
if [ $? -ne 0 ] # checking the exit status of the last command
then
  echo "User creation failed"
  exit 1
else
usermod -s /bin/bash "$user_name"  #username missing in the original code
usermod -aG www-data "$user_name"
fi

Upvotes: 1

Related Questions