Shell Scripting in Linux

Linux Kernel

A kernel is an interface between hardware and software.

The kernel is considered the heart of the Linux system. It is loaded at booting time. It is primarily responsible for controlling and allocating a machine's memory to individual processes. It takes care of scheduling the jobs carried out by the CPU.

The kernel handles data transfer from one part of the machine to another. It translates and executes the instructions from the shell and applies for permissions on file access.

What is a Shell?

A shell is like a container that acts as an interface between users and the kernel. The command-line interface is the shell.

To get the echo, the command is:

echo $0

To get all the available shells, the command is:

cat /etc/shells

To know the location of our shell, the command is:

cat /etc/passwd

Some popular shells are Windows GUI, Linux KDE GUI, and Linux sh, bash.

Types of Shells

The different types of shells:

  • Gnome - It comes with GUI. In it, the graphical option is selected during the installation process.
  • KDE - It comes with GUI. In it, the graphical option is selected during the installation process.
  • sh - It comes with a command-line without GUI.
  • bash - It is a newer version of sh known as the born-again shell.
  • csh and tcsh - They are based on C and C++ programming languages.
  • ksh - It is known as a corn shell and supports sh and bash.

Linux Shell History

The shell history is used to record all commands. It helps the system administrators to troubleshoot if there are errors or system crashes. The command for shell history:

history

To get the history page by page, the command is:

history | more

Output

linux-shellscript11

Each command in history is accompanied by a number. To run the command again from the history list, we have to put ! followed by that number. For example:

!60

To get the history of running a particular command for example grep, the command is:

history | grep chmod

Output

linux-shellscript12

The file where the history of our shell commands is saved is /home/username/.bash_history

To view other users shell history commands, we have to log in as root and execute the command:

cat /home/user-dir-name/.bash_history

Shell Scripting

A shell script is an executable file containing more than one shell commands that are run in sequence. The file contains:

  • shell.(#!/bin/bash)
  • comments.
  • commands.
  • statements.

The shell script should have executable permissions. It has to be called from an absolute path. If the script is at the current location then we have to specify ./ followed by the script name.

Basic Shell Scripts

Let us start with a basic script to display output with the echo command. First, we have to open an editor with the command:

vi scriptone

As the editor opens, we have to be in the INSERT mode, then add the script:

!#/bin/bash
echo "Linux"
# press esc and type :wq! to save

To give execute permission to the script, the command is:

chmod a+x scriptone

To run the script, the command is:

./scriptone

To run a series of commands, the script is:

!#/bin/bash
#Comments by user
whoami
echo
pwd
hostname
ls -ltr Pictures
# press esc and type :wq! to save

Output linux-shellscript

To define variables, the script should be:

!#/bin/bash
x=Chercher
y='Linux'
echo "First variable is $x"
echo "Second variable is $y"
# press esc and type :wq! to save

User Input and Output of Script

To create a script to take input from the user, the read and echo commands are used.

The input and output script is:

!#/bin/bash
# Output
echo Hello Chercher
echo Which subject
# to get input
read sub
echo Subject is $sub
# press esc and type :wq! to save

Output

linux-shellscript1

The above output shows the cursor blinking, waiting for user input. On taking Linux as input, the below output is obtained

linux-shellscript2

We can also define a variable to store the output of a command and then display it as an output with the echo command. The script is:

!#/bin/bash
#Input and Output
#hostname command stored in i variable
i=`hostname`
echo Hello the server is $i
# press esc and type :wq! to save

if-then Scripts in Linux

The if-then else statements are used for conditions. If a certain criteria is met, a block of statement is executed. Otherwise, the block of code within the else is executed.


The structure is :

If condition1 happens = do this

Otherwise = do that

Let us start with a basic script to illustrate the if-then script:

!#/bin/bash
#if-then
c=10
# to check if c = 10
if [ c -eq 10 ]
then
echo Value is 10
else
echo  Value is not 10
fi
# press esc and type :wq! to save
The if-then statement should end with fi.

To check if an error.txt file exists in the location /home/saby, the script is:

!#/bin/bash
#if-then
if [ -e /home/saby/error.txt  ]
then
echo "File exist"
else
echo  "File does not exist"
fi
# press esc and type :wq! to save

for Loop Scripts in Linux

The for loops are used to keep running until a specified number of variables. For example, if the variable = 10, then the script runs 10 times. It is mainly used for repetitive tasks.

The other type of loop available are:

  • while loop - It runs a given condition until that condition is true.
  • until loop - It runs until a given condition turns true.

Let us start with a basic script to illustrate for loop script:

#!/bin/bash
#for-loop to iterate from 1 to 5
for i in 1 2 3 4 5
do
echo "Welcome $i times"
done

The output shall be:

linux-shellscript3

The for loop script contains the do and done keyword. The loop begins with the do keyword and ends with the done keyword.

Another example of repetitive tasks script is:

#!/bin/bash
for i in eat run jump play
do
echo See myself $i
done

do-while Scripts in Linux

A do-while statement continuously runs a block of statements while a particular condition is true or met.

For example, Execute a script until 2 pm. The syntax is:

while [condition]
do
  condition1
  condition2
done

The script to run for 10 seconds:

#!/bin/bash
count=0
num=10
while [ $count -lt 10 ]
do
echo $num seconds left to stop this process $1
sleep 1
num=`expr $num - 1`
count=`expr $count + 1`
done
echo $1 process is stopped!!!

The output should be:

linux-shellscript4

Case Statement Scripts in Linux

The case statement script is an interactive way to involve the users.

For example,

if the option of a is selected = do this
if the option of b is selected = do this
if the option of c is selected = do this

The basic structure of a case statement is:

#!/bin/bash
echo
echo Please chose one of the options below
echo
echo 'a = Display Date and Time'
echo 'b = List file and directories'
echo 'c = List users logged in'
echo 'd = Check System uptime'
echo
read choices
case $choices in
a) date;;
b) ls;;
c) who;;
d) uptime;;
*) echo Invalid choice
esac

Initial output shall be:

linux-shellscript6

The above output shows the cursor blinking, waiting for user input.

Here on selecting option a, the date command is executed. If b is selected ls command is executed. If c is selected who command is executed and if d is selected uptime is executed.

If the user selects * the Invalid choice message is thrown.

linux-shellscript7

Check Remote Servers Connectivity in Linux

We can create a script to verify the status of the remote host. We shall have a script that shall ping a remote host and notify it.

We shall use a ping script that goes out on the remote host, then pings an IP address to verify if a host is available or not.

#!/bin/bash

ping -c1 192.168.1.1
        if [ $? -eq 0 ]
        then
        echo OK
        else
        echo NOT OK
        fi
:wq!

Output

linux-shellscript9

Here it shows 1 received with no error. Also, it displays OK as per the if condition.

Let us change the IP address such that it is not reachable.

#!/bin/bash

ping -c1 192.168.1.235
        if [ $? -eq 0 ]
        then
        echo OK
        else
        echo NOT OK
        fi
:wq!

Output :

linux-shellscript8

Here it shows 0 received with +1 errors. It gives the message Destination Host Unreachable so the host is unavailable. Also, it displays NOT OK as per the if condition.

If we do not want these messages output, we have to add &> /dev/null to the script:

ping -c1 192.168.1.1 &> /dev/null
        if [ $? -eq 0 ]
        then
        echo OK
        else
        echo NOT OK
        fi

We can store the host IP address in a variable in the script.

hosts="192.168.1.235"
ping -c1 $hosts &> /dev/null
        if [ $? -eq 0 ]
        then
        echo $hosts is OK
        else
        echo $hosts is NOT OK
        fi
:wq!

Output
linux-shellscript10

It only displays NOT OK as per the condition

To deal with multiple hosts, we shall keep the host address in a separate file. Then create a script such that it can access the file with multiple host addresses and iterate over the hostname address list.

#!/bin/bash
#path of file with host address list
IPLIST="path_to_the_Ip_list_file"

#iterate through the contents of the file obtained with cat command
for ip in $(cat $IPLIST)

do
   ping -c1 $ip &> /dev/null
   if [ $? -eq 0 ]
   then
   echo $ip ping passed
   else
   echo $ip ping failed
   fi
done
:wq!

Aliases in Linux

An alias is a popular command used to cut down on lengthy and repetitive commands.

To create an alias for ls -al, the command is:

alias l ="ls -al"

To run the command we simply write l.

To create an alias for multiple commands in one short, the command is:

alias pl = "pwd; ls"

To get the list of all directories with the help of an alias, the command is:

alias dir ="ls -l | grep ^d"

To view get all the aliases, the command is:

alias

To remove a previously created alias, the command is:

unalias alias_name

User and Global Aliases

There are two types of aliases. First is the one which applies to a specific user profile. The other type applies to all who have an account on the system.

To create a user alias we have to set it up inside /home/user/.bashrc. To create a global alias, we have to set it up inside /etc/bashrc.

To set up a user alias for hostname, execute the below command from /home/user:

vi .bashrc

Inside the editor, add the command:

alias hh="hostname"
:wq!

Now, log off from the current terminal session and open a new session to use the alias hh.

To set up a global alias for hostname, we have to log in as root and execute the below command:

vi /etc/bashrc

Inside the editor, add the command:

alias hh="hostname"
:wq!

Now, log off from the current terminal root session and open a new session to use the alias hh.

About Author :

Myself Debomita Bhattacharjee, an IT employee with 6+ years of experience in Software industry. My area of interest is Automation testing and Front End Development.

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions