News

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

NUM1=2
NUM2=2
if [ $NUM1 -eq $NUM2 ]; then
echo    “Both Values are equal”
else
echo     “Values are NOT equal”
fi
[/sourcecode]
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
S1=”User”
#Declare string S2
S2=”Developer”

if [ $S1 = $S2 ]; then
echo “Both Strings are equal”
else
echo “Strings are NOT equal”
fi
[/sourcecode]
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
testfile=”./my_file”
if [ -e $my_file ]; then
echo “The specified file exists”
else
echo “The specified file does not exist”
fi
[/sourcecode]
et us understand how the script executes in both cases. Save the above script in a file ‘script_12.sh’.
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 ~]# ./script_12.sh
The specified file does not exist
[/sourcecode]
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 ~]# ./script_12.sh
The specified file exists
[/sourcecode]
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 $?
[/sourcecode]
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 $?
0
[root@localhost ~]#
[/sourcecode]
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”]

×