Shell Scripting - insight and walkthrough

Shell Scripting - insight and walkthrough

Hello, readers in the last blog I explained about shell and some important Linux commands. In this blog, I will start from the shell and then go deep in shell scripting.

Shell what is it

Shell in general terms is a command line interpreter which takes command from the user and communicates with the kernel to perform the task.

Types of shell

some of the important types of shell are:-

  1. /bin/sh:- Bourne shell

  2. /bin/bash:- Bourne again shell

  3. /bin/csh:- C shell

  4. /bin/ksh:- korn shell

there are some other types of shell also available but these are some important to know.

Shell scripting:- an introduction

what is a shell script

shell script is a file that contains a series of Linux commands to perform any action. it has an extension of .sh and is an executable file.

when to write shell scripts

  1. Backups

  2. Log monitoring

  3. Checking Disk Space

  4. Periodic reports

  5. Offsite backups

  6. Purging old data

  7. checking for database locks

  8. Killing runaway processes

  9. Storing OS information such as performance stats, disk usage etc in the database

  10. Regular monitoring tasks (multiple times a day).

Structure of shell scripts

Any shell script is started with she bang then it contains the author name date of creation variable declaration and at last logic or the program that we want to write.

Shebang

#! :- shebang is the first line in the shell script and is used to specify which shell to use to run the script.

The "shebang" is a special comment. Since it is a comment it will not be executed when the script is run. Instead, before the script is run, the shell calling the script will check for the #! pattern. If found it will invoke the script using that interpreter. If no #! is found most shells will use the current shell to run the script.

Variables

The variable is a placeholder for storing data. The value of the variable can be changed during the program execution. The value assigned could be a number, text, filename, device, or any other type of data.

  • The syntax for creating variables :

variablename=value

  • Variable name should be preceded with $ sign

  • example $a=10 (no space on either side of = sign ).

  • we can capture the output of a command into a variable

    using the back quote tab `` ex:- user = `whoami`

Arithematics on variables

We can perform various operations on variables.

Syntax for performing operation on variables is :-

expr operand1 operator operand2

expr is the command used when we have to perform arithmetic operations on the variable.

Operators allowed in shell scripting

addition+
subtraction-
multiplication*
division/
modulus%

examples of arithmetic operation

  1. expr 10 + 2 o/p = 12

  2. $a=2

    expr $a + 10 o/p = 12

  3. expr 10 \* 2 o/p = 20

  4. $( (10+2) ) o/p = 12

  5. $( ( 10 + 2 ) ) o/p = 12

User Input

read command is used to take user input.

syntax of read command is :- read variable 1 variable 2 ....

ex :

$ vi read.sh 

#Script to read your name from key-board #

echo "Your first name please:" 
read fname

echo "Hello $fname, Lets be friend!"

we can also take input from the command line argument using special variable $1 - $10.

special variables and their description.

VariableDescription
$0Thefilename of the current script.
These variables correspond to the arguments with which a script was invoked. Here n is a positive decimal number corresponding to the position of an argument (the first argument is $1, the second argument is $2, and so on).
$#Thenumber of arguments supplied to a script.
$*All the arguments are double quoted. If a script receives two arguments, $* is equivalent to $1 $2.
All the arguments are individually double quoted. If a script receives two arguments, $@ is equivalent to $1
$?Theexit status of the last command executed.
The process number of the current shell. For shell scripts, this is the process ID under which they are executing.
$!Theprocess number of the last background command.

Mathematical operator in shell


-eq    is    equal to    5    == 6    If    [    5    -eq    6    ]
-ne    is    not equal to    5    != 6    If    [    5    -ne    6    ]
-lt    is    less than    5    < 6    If    [    5    -lt    6    ]
-le    is less than or equal to    5    <= 6    If    [    5    -le    6    ]
-gt    is    greater than    5    > 6    If    [    5    -gt    6    ]
-ge    is or    greater than equal to    5    >= 6    If    [    5    -ge    6    ]

String operators in shell

OperatorDescriptionExample
\=Checks if the value of two operands are equal or not, if yes[ $a = $b ] is not true.
!=Checks if the value of two operands are equal or not, if values are not equal then[ $a != $b ] is true.
-zChecks if the given string operand size is zero. If it is[ -z $a ] is not true.
-nChecks if the given string operand size is non-zero. If it is non-zero length then it[ -z $a ] is not false.
strCheck if str is not the empty string. If it is empty then it[ $a ] is not false.

File operators in shell

OperatorDiscriptionExample
-r fileChecks if file is readable if yes then condition becomes true.[ -r $file ] is true.
-w fileCheck if file is writable if yes then condition becomes true.[ -w $file ] is true.
-x fileCheck if file is execute if yes then condition becomes true.[ -x $file ] is true.
-s fileCheck if file has size greater than 0 if yes then condition becomes true.[ -s $file ] is true.
-e fileCheck if file exists. Is true even if file is a directory but exists.[ -e $file ] is true.
-f fileCheck if file is an ordinary file as opposed to a directory or special file if yes then condition becomes true.[ -f $file ] is true.

Conditional is shell

The syntax of the conditional statement in shell is given as

  1. first type
if [ expression ] then
Statement(s) to be executed if expression is true
fi
  1. second type
if [ expression ] then
Statement(s) to be executed if expression is true
elif [ expression ] then 
Statement(s) to be executed if expression is true
else 
Statement(s) to be executed if expression is true

fi

Looping in shell scripting

There are three looping statements in shell scripting

  1. while

  2. for

  3. until

while

while loop is executed until the condition provided to it is true.

syntax for a while loop is given as

while condition-command do
command1 command2
...

done

FOR

for loop in shell scripting is used as

for var in word1 word2 ... wordN do
Statement(s) to be executed for every word.
Done

UNTIL

until loop is executed when condition is evaluated as false

until command do
Statement(s) to be executed until command is true Done

shell scripting like any other programming language also have break and continue statements

Functions in shell scripting

  • Shell scripting also supports function creation and doing work using functions

  • The syntax for declaring a function is given as:

function function_name () { 
list of commands
}

example :

#!/bin/sh
# Define your function here 
function Hello () {
echo "Hello World"
}
# Invoke your function
Hello
  • We can also pass parameters to the function

example:

#!/bin/sh
# Define your function here 
function Hello () {
echo "Hello World $1 $2" #here $1 and $2 are used to take two parameters passed by user
}
# Invoke your function 
Hello Shyam Ram  #here Ram and shyam are parameters
  • The return command is used to return the value from a function.

    example:

#!/bin/sh
# Define your function here 
function Hello () {
echo "Hello World $1 $2" 
return 10
}
# Invoke your function
 Hello  Shyam Ram  #here Ram and shyam are parameters
# Capture value returnd by last command 
ret=$?
echo "Return value is $ret"

This is the information about shell scripting and below are some project which i have made still there are some more projects other than mentioned here.

# !/bin/bash
#this project shows uses of user input printing input values and then simple conditional statements
b=18
echo "$b"
echo "enter name"
read name
echo "enter age"
read age
echo "enter your usn"
read usn
echo "gender"
read gender 
echo "student details are"
echo "name = $name"
echo "age= $age"
echo "usn =$usn"
echo "gender= $gender"

if [[ $age -lt b ]]
then 
    echo "not"
else
    echo "yes"
fi
 #!/bin/bash

#this will show the use of loops and conditionals

# AUTHOUR : SHYAM PANDEY
# DATE : 4 NOV 2023
#TITLE: Script to print foo,bar and foobar according to given conditions

for ((i=0; i<20;i++)) do

        if [[ $((i%3)) == 0 && $((i%5)) == 0 ]];
        then
                echo "FooBar"
        elif [[ $((i%5)) == 0 ]];
        then
                echo "Bar"
        elif [[ $((i%3)) == 0 ]];
        then
                 echo "Foo"
        else
                echo "$i"

        fi
done
#!/bin/bash
#project to create a new directory to place desired file in it 

echo "Welcome To File_Installer"

sleep 1

echo "Please Enter Your Project Name "

sleep 2

read projectname

mkdir $projectname #root folder
echo "Root folder created..."
cp index.html $projectname/index.html
cp main.css $projectname/main.css
echo "File has been Copied...."

cd $projectname
#!/bin/bash 

# Author :- SHYAM PANDEY
#DATE:- 07-11-2023

# Send an email to a concerned person if there are more than 5 users logged on to the system 

no_of_users_logged_in=`who | wc -l`
if [ ${no_of_users_logged_in} -gt 5 ]; 
then 
    subject='High System Load'
    who > /tmp/list_of_users.txt
    mail -s ${subject} user@gmail.com </tmp/list_of_users.txt
fi

# remove temporary file which we have created to keep the log. 

rm -f /tmp/list_of_users.txt
#!/bin/bash

# Author :- SHYAM PANDEY
# DATE:- 07-11-2023

# Write a shell Script to pass username to shell script and check whether that user exists or not in your system

echo "Enter user name" read usr
cat /etc/passwd|grep –wo ^$usr &>/dev/null if [ $? -eq 0 ]
then
echo "$usr exists"
else
echo "$usr does not exists"
fi