[Linux] : 7 things you will learn as you start writing a simple Shell script

Updated on September 3, 2017

A system administrator will always think of automating most of his tasks so that the routine jobs are completed easily and he can concentrate on some other critical things. One such task is Unix account creation. Here we will see how we can create an Unix account using shell script. In this journey of creating shell script, even though the task seems to be simple, you will learn many things !

1. Follow standard guidelines during scripting for better readability

Most other programming languages like C, C++, JAVA have a set of “Best Practices” that would be followed during coding. However as the name suggests shell scripting is kind of a programs written for a special run-time environment at quick time Quick time means very less follow the rules. Following best practices will make your script more readable, reusable and maintainable.

So in this script we will be using functions to modularise the code. Below code snippet for the function usage() :

usage()
{
echo "Usage: $PROGNAME  [options]
Options:
-u username,            Provide name for new user account creation
-p password,            Provide complex password
-h help,                display this help message and exit      "
exit 1;
}

This usage function is called whenever a help is required in executing the script or for wrong arguments etc.,

Shell Script Usage function
Shell Script Usage function

2. How to accept arguments in a shell script

In a shell script accepting arguments are done as below :

$0 - Script Name
$1 - First argument
$2 - Second argument
$# - No. of arguments
$@ - All arguments

Ex:

Tue Oct 29>$./account_creation.sh username password

In the above example $0 is account_creation.sh, $1 is username and $2 is password. $# will return 2 and $@ return all the arguments.

3. Command Line options using “Getopt” in shell script

Providing command line options is a better way of presenting your script to the user. You can write scripts to support both short and long command line options. For eg: to display a help message, you can use either “-h” or “–help” option. A typical convention is that long options are preceded with a double hash and small ones with single dash. Below is the code :

while getopts ":h:u:p:" OPTION
do
        case "$OPTION" in
        h)
                usage
                ;;
        u)
                USERNAME=${OPTARG}
                ;;
        p)
                PASSWORD=${OPTARG}
                ;;
        \?)
                usage
                ;;
        esac
done

The getopts command is a Korn/POSIX Shell built-in command that retrieves options and option-arguments from a list of parameters.  Read more about getopts here. In simple for each command line option, the loop gets executed and the corresponding value for each option gets stored in assigned variables. Below is the code snippet to check whether the parameters passed are empty :

shift $((OPTIND-1))
if [ -z "${USERNAME}" ] || [ -z "${PASSWORD}" ]; then
    usage
fi

4. How to run Linux commands from shell script

Here useradd is a Linux command used to create an account.

/usr/sbin/useradd -m ${USERNAME}

Here you need to notice that if the user already exists, then you might get few warnings as stderr which is shown in the below image :

User Creation Error Linux Shell
User Creation Error Linux Shell

5. How to ignore/redirect stdout and stderr to log-file

Bash and other modern shell provides I/O redirection facility. Linux standard I/O stream numbers are as follows :

HandleNameDescription
0stdinStandard input
1stdoutStandard output
2stderrStandard error

a. Redirecting stderr stream to a file :

$script 2> error.log

b. Redirecting stdout stream to a file :

$script 1> output.log

c. Redirect both stderr and stdout to a file :

$script  &>file.out

If you want to just ignore these stderr and stdout messages, then redirect it to /dev/null instead of file.

$script 2>/dev/null

6. How to check for the command’s successfull execution in a shell script

$? is the return code (status code) of the last command or script executed. 0 == success, any other number means a failure

7. Conditional statements like if/else in shell script

Most programming and scripting languages have some sort of if/else expression and so does the shell scripting. The following table shows the different expressions allowed.

-eqequal to
-nenot equal to
-ltless than
-leless than or equal to
-gtgreater than
-gegreater than or equal to

Note: Unlike most other languages, spaces are very important when using an if statement in shell scripting.

Below code does check for the status code of the last command and on success moves further to create password. On setting password successfully, we shall put a message on the terminal for successful completion of the activity.

# Create User Account
/usr/sbin/useradd -m ${USERNAME} 2>/dev/null
if [ $? -eq "0" ]; then
        echo -e ${PASSWORD} | /usr/bin/passwd ${USERNAME} --stdin >/dev/null
        if [ $? -eq "0" ]; then
             echo "User ${USERNAME} created sucessfully"
        fi
fi

Complete Script : Download link

Checkout our other interesting articles on LINUX :

Bash shell quick keyboard shortcuts – Linux Tips

8 Funny Linux commands – You’ll love it!

Best practices when running rm -rf command on linux

Linux System Administrator Commands

How to add a progress bar to copy and move commands in Linux?

How to Sync Linux Server Time with Network Time Server

How to configure yum to use CentOS repository in RHEL machine

Best Tools To Recover Data [Windows, Linux, DOS, MAC OS X]

Was this article helpful?

Related Articles

Leave a Comment