Help - Search - Members - Calendar
Full Version: Shell Script
Linuxhelp > In The Community > General Discussion
netcom88
I'm still in the process of learning how to write shell scripts. I have a script for adding a user to the system ... Could anyone help me break down this script and explain what each lines does? I would greatly appreciate it!

if [ $(id -u) -eq 0 ]; then
read -p "Enter username : " username
read -s -p "Enter password : " password
egrep "^$username" /etc/passwd >/dev/null
if [ $? -eq 0 ]; then
echo "$username exists!"
exit 1
else
pass=$(perl -e 'print crypt($ARGV[0], "password")' $password)
useradd -m -p $pass $username
[ $? -eq 0 ] && echo "User has been added to system!" || echo "Failed to add a user!"
fi
else
echo "Only root may add a user to the system"
exit 2
fi
michaelk
A good place to start is to read advanced bash programming. http://tldp.org/LDP/abs/html/ It will explain the fundamentals of bash programming.
search for conditional statements i.e. if then else,
input statements i.e. read
and
environment variables i.e. #?

In a nutshell.
adduser is a utility to add a user. It can only be run as root and root's id is always 0 (zero).
egrep is a pattern matching console utility. In this case it is used to find if a user already exists.
perl is a shell language and crypt is a perl built in DES encryption function. In this case it is encrypting the password.
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Invision Power Board © 2001-2017 Invision Power Services, Inc.