Table of contents
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:-
/bin/sh:- Bourne shell
/bin/bash:- Bourne again shell
/bin/csh:- C shell
/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
Backups
Log monitoring
Checking Disk Space
Periodic reports
Offsite backups
Purging old data
checking for database locks
Killing runaway processes
Storing OS information such as performance stats, disk usage etc in the database
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
expr 10 + 2 o/p = 12
$a=2
expr $a + 10 o/p = 12
expr 10 \* 2 o/p = 20
$( (10+2) ) o/p = 12
$( ( 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.
Variable | Description | |
$0 | The | filename 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). | ||
$# | The | number 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 | ||
$? | The | exit 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. | ||
$! | The | process 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
Operator | Description | Example |
\= | 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. |
-z | Checks if the given string operand size is zero. If it is | [ -z $a ] is not true. |
-n | Checks if the given string operand size is non-zero. If it is non-zero length then it | [ -z $a ] is not false. |
str | Check if str is not the empty string. If it is empty then it | [ $a ] is not false. |
File operators in shell
Operator | Discription | Example |
-r file | Checks if file is readable if yes then condition becomes true. | [ -r $file ] is true. |
-w file | Check if file is writable if yes then condition becomes true. | [ -w $file ] is true. |
-x file | Check if file is execute if yes then condition becomes true. | [ -x $file ] is true. |
-s file | Check if file has size greater than 0 if yes then condition becomes true. | [ -s $file ] is true. |
-e file | Check if file exists. Is true even if file is a directory but exists. | [ -e $file ] is true. |
-f file | Check 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
- first type
if [ expression ] then
Statement(s) to be executed if expression is true
fi
- 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
while
for
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