Shell scripting for system administrators: the basics

For system administrators shell scripting can be a very useful way to drastically improve workflow. Join Swayam Prakasha to find out how you can employ some fundemental tips and techniques to make your life easier…

SS Figure 1

We also can use various arithmetic operators inside a shell script. The following table explains these various arithmetic comparison operators:

The following example shows how one can use these operators in a shell script:
[sourcecode language=”bash”]#!/bin/sh

# declare integers

if [ $NUM1 -eq $NUM2 ]; then
echo    “Both Values are equal”
echo     “Values are NOT equal”
We can also compare two strings using various string comparison operators. The following table lists some of the string comparison operators…

Here’s an example to help with our understanding:
[sourcecode language=”bash”]#!/bin/sh

#Declare string S1
#Declare string S2

if [ $S1 = $S2 ]; then
echo “Both Strings are equal”
echo “Strings are NOT equal”
We can also write a shell script to check whether a file exists or not. The option ‘-e file’ is used to check for file existence. The following shell script checks for the existence of a test file (in this case, my_file)
[sourcecode language=”bash”]#!/bin/sh
if [ -e $my_file ]; then
echo “The specified file exists”
echo “The specified file does not exist”
et us understand how the script executes in both cases. Save the above script in a file ‘’.
Case 1: When test file does not exist
[sourcecode language=”bash”][root@localhost ~]# ll my_file
ls: my_file: No such file or directory
[root@localhost ~]# ./
The specified file does not exist
Case 2: When test file exists
[sourcecode language=”bash”][root@localhost ~]# touch my_file
[root@localhost ~]#
[root@localhost ~]# ll my_file
-rw-r–r– 1 root root 0 Jun 20 23:56 my_file
[root@localhost ~]# ./
The specified file exists
In some cases, we might be interested in knowing the exit status – this gives a clear indication whether a script (or a command) has executed successfully or not. In most case, for a successful execution, the exit status will be 0. One can get the exit status by using the following command:
[sourcecode language=”bash”]$ echo $?
Here is an example to see the exit status after a command execution:
[sourcecode language=”bash”][root@localhost ~]# cal
June 2010

Su Mo Tu We Th Fr Sa
1  2  3  4  5
6  7  8  9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30

[root@localhost ~]# echo $?
[root@localhost ~]#
In the above example, we tried to print the exit status after the ‘cal’ command was executed.

For more tutorials from linux User & Developer click here, or go here to see what else featured in issue 90.

[twitter username=”linuxusermag”]