Shell Scripting
Shell Scripting
Shell Scripting
What is Shell?
1. Shell is responsible to read commands/applications provided by user.
2. Shell will check whether command is valid or not and whether it is properly used or not. If
everything is proper then shell interpreters converts that command into kernel
understandable form. That interpreted command will be handover to kernel.
3. Kernel is responsible to execute that command with the help of hardware. Shell acts as
interface between user and kernel.
4. shell + kernel is nothing but operating system.
Types of Shells:
1) Bourne Shell:
2) BASH Shell:
3) Korn Shell:
4) CShell:
5) TShell:
T means Terminal.
It is the advanced version of CShell.
This is the most commonly used shell in HP UNIX.
By using tcsh command, we can access this shell.
6) Z Shell:
Developed by Paul.
By using zsh command we can access this shell.
Note: The most commonly used shell in Linux environment is BASH. It is more powerful than
remaining shells.
$ echo $0
Location
$ echo $SHELL
2. We can also check the default shell information inside /etc/passwd file
$ cat /etc/passwd
Note: you can only into those shell which are present on your OS.
vi test.sh
$ /bin/bash ./test.sh
$ bash ./test.sh
$ /bin/bash /home/Rahulsoft/scripts/test.sh
$ ./test.sh # default shell is bash
Note: The default shell is bash. Hence bash is responsible to execute our script.
Instead of bash, if we want to use Bourne shell then we have to use the following Command
$ /bin/sh ./test.sh
$ sh ./test.sh
Importance of Sha-Bang:
By using sha-bang, we can specify the interpreter which is responsible to execute the script.
# Sharp
! Bang
#! Sharp Bang or Shabang or Shebang
#! /bin/bash It means the script should be executed by bash
#! /bin/sh It means the script should be executed by Bourne Shell
#! /usr/bin/python3 It means the script should be executed by Python3 interpreter
If we write shabang in our script at the time of execution, we are not required to provide command
to execute and we can execute script directly.
Q1) Write a Python Script and execute without shabang and with shabang?
test.py
Without Shabang:
$ python3 ./test.py
$ python3 /home/Rahulsoft/scripts/test.py
With Shabang:
$ ./test.py
$ /home/Rahulsoft/scripts/test.py
demo.sh
$ ./demo.sh
It is equivalent to $ rm ./demo.sh
demo.sh will be removed as this script executed by rm command.
Q3) Write and Run Shell Script that Prints Current System Date (DD-MM-YY).
Shell Variables
Variables are place holders to hold values.
Variables are key-value pairs.
In Shell programming, there are no data types. Every value is treated as text type/ String
type.
1)Environment Variables:
These are predefined variables and mostly used internally by the system. Hence these
variables also known as System variables.
But based on our requirement, we can use these variables in our scripts.
We can get all environment variables information by using either env command or set
command.
Variable Scopes:
There are 3 scopes available for variables:
Session Scope
User Scope
System Scope
1) Session Scope:
The variables which are declared in the terminal are said to be in session scope.
Once we close the terminal (ie exit session) automatically all variables will be gone.
$ X=10
$ Y=10
2) User Scope:
The variables which are declared inside .bashrc file, are said to be in user scope.
These variables are available for all sessions related to current user. These variables cannot
be accessed by other users.
vi .bashrac
....
export Name=Rahul
3) System Scope:
If the variable available for all users and for all sessions, such type of variables are said to be
in system scope.
We have to declare these variables inside /etc/profile file. But to edit this file compulsory
root permissions must be required.
...
export NAME=Rahul
export COURSE=DevOps
Variable Substitution:
Syntax:
$variablename
${variablename}
Ex :
O/P:
Note: If we use single quotes then variable substitution won't be happened. But we can use double
quotes.
Command Substitution:
We can execute command and we can substitute its result based on our requirement by using
command substitution.
Syntax:
The arguments which are passing from the command prompt at the time of executing our
script, are called command line arguments.
$ ./test.sh you need to study hard
The command line arguments are you,need,to ,study,hard.
Note: The main purpose of command line arguments is to customize behaviour of the script.
find_length_of_given_word.sh
This script will work only for string: Ramesh but below script can take word form user as cmd line
argument and print it’s length
Approach-1
test.sh
o/p:
Approach-2
o/p:
Note:
read -p : Just to display prompt message
read -s : It hides input on screen which is provided by end user.
o/p:
Write a Script that takes a String from the End User and Print its Length?
Operators
1)Arithmetic Operators
+ Addition
- Substraction
* Multiplication (we should use \* as it is wild card character)
/ Division
% Modulo Operator
Assignment operator: =
Note: Except assignment operator, for all operators we have to provide space
before and after operator.
(File Test)
-s file : True if the file exists and has a size greater then o
-f file : True if the fiel exists and is not a directory
-d file :True if the fiel exists and is a dir
-c file :True if the fiel exists and is a character special file
-b file: True if the fiel exists and is a block special file
-r file: True if the fiel exists and you have read permission on it
-w file: True if the fiel exists and you have write permission on it
-x file: True if the fiel exists and you have execute permission on it
-k file: True if the fiel exists and its sticky bit is set
(String Test)
string1 = string 2 : True if the string are same
string 1!= String2 : True if the strign are not same
-n string : True if the length of the string is greter than 0
-z string : True if the lenght of the string is zero
string : True if the string is not null string
o/p:
4) By using []:
Note: All the above 4 approaches will work only for integral arithmetic (only for integer numbers).
bc Command:
bc means binary calculator.
We can start binary calculator by using bc command.
ctrl+d To exit bc
Q]Write a Script to Read 4 Digit Integer Number and Print the Sum of Digits Present in that Number?
O/p:
Control Statements
1. if statement
2. case statement
3. while loop
4. for loop
5. until loop
6. break
7. continue
8. exit
if Statement:
There are 4 types of if statements
simple if
if-else
nested if
ladder if
1) simple if:
if [ condition ]
then
action
fi
O/P:
Note:
x=10 Assignment
x = 10 Comparison
2) if -else:
if [ condition]
then
else
fi
3) Nested if:
if [ condition ]
then
.........
.........
if [ condition ]
then
.........
else
........
fi
.....
else
......
fi
4) ladder -if:
if [condition]
then
action-1
elif [ condition ]
then
action-2
elif [ condition ]
then
action-3
else
default action
fi
o/p
Q]Write a Script that Reads an Integer Number and Check whether the given Number is +ve Number
OR -ve Number?
Q]Write a Script that Reads an Integer Number and Checks whether it is Even Number OR not?
O/P:
Write a Script to Test whether the given String is Empty OR not? If it is not Empty then Print its
Length.
O/P:
2)case Statement:
If multiple options are available then it is not recommended to use nested if-else
statements. It increases length of the code and reduces readability.
To handle such type of requirements we should go for case statement.
Syntax:
case $variable in
option1 )
action-1
;;
option2 )
action-2
;;
option3 )
action-3
;;
)
default action
;;
esac
Note:
1. space is optional while defining options.
2. ;; can be used to come out of case statement.
3. ;; is mandatory for all options except for default option.
4. If we take default option at the beginning, then for any input the same default
option will be executed.
Q]Write a script to read a number from 0 to 9 and print equivalent English word?
O/P:
Iterative Statements:
If we want to execute a group of commands multiple times then we should go for iterative
statements.
There are 3 types of iterative statements
1. while loop
2. until loop
3. for loop
while Loop:
If we don't know the number of iterations in advance, then we should go for while
loop.
Syntax:
while [ condition]
do
body
done
As long as condition is true, then body will be executed. Once condition fails then only
O/P:
Q]Write a Script to generate Numbers until Limit which is provided by End User?
O/P:
Note: If we don't want to perform any operation for a particular amount of time (i.e just
pausing is required) then we should go for sleep command. The argument to the sleep
command is seconds.
break Statement:
Based on some condition, if we want to break loop execution (i.e to come out of loop) then
we should go for break statement.
O:P
continue Statement:
We can use continue statement to skip current iteration and continue for the next iteration.
O/P:
until Loop:
It is opposite to while loop.
Syntax:
until [ condition ]
do
body
done
The body will be executed as long as condition returns false. Once condition returns true,
O/P:
for Loop:
If we want to perform some action for every item in the given list, then we should go for for loop. It is
similar to Java's for-each loop.
Syntax:
do
action
done
O/P:
do
body
done
New
do
body
done
O/P:
Arrays
If we want to represent a group of values with a single name then we should go for arrays concept.
element is zero.
Note:
fruits[4]="Sapota"
Such type of repeated code we have to define inside a block and we can call that block where ever
required. This block of commands is nothing but function. Hence function is nothing but a block of
repeatable commands.
Advantages of Functions:
1st Way:
function function_name()
commands
2nd Way:
function_name()
{
commands
O/P:
$1 First Parameter
$2 Second Parameter
$@ All Paramters
$* All parameters
$# Total number of parameters
$0 It is script name but not function name
O/P: