Shell Scripting

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 33

Shell Scripting

What is Shell and Types of Shells:

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:

There are multiple types of shells are available.

1) Bourne Shell:

 It is developed by Stephen Bourne.


 This is the first shell which is developed for UNIX.
 By using sh command we can access this shell.

2) BASH Shell:

BASH  Bourne Again Shell.

 It is advanced version of Bourne Shell.


 This is the default shell for most of the linux flavours.
 By using bsh command we can access this shell.

3) Korn Shell:

 It is developed by David Korn.


 Mostly this shell used in IBM AIX operating system.
 By using ksh command, we can access this shell.

4) CShell:

 Developed by Bill Joy.


 C meant for California University.
 It is also by default available with UNIX.
 By using csh command, we can access this shell.

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.

1. How to Check Default Shell in our System?

$ echo $0

Location

$ echo $SHELL

2. We can also check the default shell information inside /etc/passwd file

$ cat /etc/passwd

3. How to check all available Shells in our System?


/etc/shells file contains all available shells information.
$ cat /etc/shells
4. How to Switch to other Shells?
Based on our requirement we can switch from one shell to another shell.

Below is the list of cmd to switch into particular shell:

Shell Name Cmd


The Bourne Shell Sh
Bourne-Again Shell Bash
T Shell Tcsh
Z Shell Tsh
The Korn Shell Ksh

Note: you can only into those shell which are present on your OS.

What is Shell Script, Sha-Bang and First Script:


What is Shell Script:
 A sequence of commands saved to a file and this file is nothing but shell script.
 Inside shell script, we can also use programming features like conditional statements,
loops, functions etc. Hence, we can write scripts very easily for complex
requirements also.
 Best suitable for automated tasks

How to write and run Shell Script:


Step - 1: Write script

vi test.sh

Step - 2: Provide execute permissions to the script:

$ chmod a+x test.sh

Step - 3: Run the script

We can run the script in multiple ways

 $ /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

Q2) Consider the following Script:

demo.sh

If we execute this script what will happen?

 $ ./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.

All variables are divided into 2 types:

1. Environment variables / predefined variables


2. User defined variable

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.

Demo Script to Use some Environment Variables:

Run the program:

2)User defined Variables:


Based on our programming requirement, we can define our own variables also.
Rules to define Variables:
 It is recommended to use only UPPER-CASE characters.
 If variable contains multiple words, then these words should be separated with symbol.
 Variable names should not start with digit.
 We should not use special symbols like -, @, # etc

How to define constant /Readonly Variables:


We can define read only variables by using readonly keyword.
$A=1000
$readonly A
$A=300
bash: A: readonly variable
If the variable is readonly then we cannot perform reassignment for that variable. It will
become constant.

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.

$ sudo gedit /etc/profile

...

export NAME=Rahul

export COURSE=DevOps

Variable Substitution and Command Substitution:

Variable Substitution:

Accessing the value of a variable by using $ symbol is called variable substitution.

Syntax:

 $variablename
 ${variablename}

Recommended to use ${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:

 Old style: `command `


 These are backquotes but no single quotes
 New Style: $(command)

Command Line Arguments:

 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.

Inside script we can access command line arguments as follows:

 $# Number of Arguments (5)


 $0  Script Name (./test.sh)
 $1  1st Argument (you)
 $2  2nd Argument (need)
 $3  3rd Argument (to)
 $4 4th Argument (study)
 $5 5th Argument (hard)
 $*  All Arguments (you need to study hard)
 $@ All Arguments (you need to study hard)
 $? Represents exit code of previously executed command or script.

Difference between $@ and $*:


 $@  All command line arguments with space separator
"$1" "$2" "$3" ...
 $* All command line arguments as single string
"$1c$2c$3c.."
Where c is the first character of the Internal Field Separator (IFS).
 The default first character is space.

How to Check Default IFS:

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

How to Read Dynamic Data from the User:


By using read keyword we can read dynamic data from the end user.

Without Prompt Message:

With Prompt Message:

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

Relational Operators: (Numeric Comparison Operators)


 -gt Greater than
 -ge Greater than or equal to
 -lt Less than
 -le Less than or equal to
 -eq Is equal to
 -ne Not equal to

These operators return Boolean value (true/false)


Logical Operators:
 -a Logical AND
 -o Logical OR
 ! Logical Not

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

These operators return boolean value (true/false)


Logical Operators:
 -a Logical AND
 -o Logical OR
 ! Logical Not
How to perform Mathematical Operations:
There are multiple ways
 By using expr keyword
 By using let keyword
 By using (())
 By using []

1) By using expr Keyword:


expr means expression and it is a keyword.

o/p:

Note: While using expr keyword, $ symbol is mandatory.


Space must be required before and after + symbol.

2)By using let Keyword:

3)By using (()):


Here space and $ symbol, both are optional.

4) By using []:

Here also space and $ symbol, both are optional

Note: All the above 4 approaches will work only for integral arithmetic (only for integer numbers).

If we want to perform floating point arithmetic then we should use bc command.

bc Command:
 bc means binary calculator.
 We can start binary calculator by using bc command.

ctrl+d  To exit bc

Note: bc can perform both integral and floating-point arithmetic.

Script for floating Point Arithmetic:


O/P:

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

If condition is true then only action will be executed.

Write a Greeting Message for specific User:

O/P:

Note:

 x=10  Assignment
 x = 10 Comparison

2) if -else:
if [ condition]

then

action if condition is true

else

action if condition is false

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

Q2) Write a Script to find Greater of 2 Numbers?

o/p

Q]Write a Script to find Greater of 3 Numbers?


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?

Q]Script to Test whether the given File Exists 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

loop will be terminated.

Write a Script to Print Numbers from 1 to 10

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.

Q]Write a Script to Display Timer (Digital Timer)?


Note: To use escape characters like \n and \t, we should not use echo and we should use
printf command.
Note: true and false are keywords which represents boolean values.

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,

then loop will be terminated.

Q]Write a Script to Print 1 to 5 by using until Loop?

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:

for variable in item1 item2 item3... itemN

do

action

done

Q]To print numbers from 1 to 5. .

O/P:

Alternative Syntax of for Loop (Advanced for Loop):


1) Old Style of for Loop:

for variable in item1 item2 ... itemN

do

body

done

New

Advanced for Loop:

for ((i=1; i<10; i++))

do

body

done

Q]Write a Script to Print Numbers from 0 to 4 by using advanced for Loop?

O/P:
Arrays
If we want to represent a group of values with a single name then we should go for arrays concept.

How to Create Arrays:

1. If we know elements at the beginning:


courses=(Java Python Linux Shell)
2. If we don't know elements at the biginning:
courses[0]=Java
courses[1]=Python
courses[2]=Linux
courses[3]=Shell

3. The index values need not be consecutive. We can take randomly.


courses[10]=DataScience
courses[20]=Devops

How to Access Elements:


We can access array elements by using index which is zero based.

i.e the index of first

element is zero.

 ${courses[0]}  First element


 ${courses[1]}  Second element
 ${courses[@]} All elements present inside array.
 ${courses[*]}  All elements present inside array into a single string separated by first
character in IFS(Internal Field Separator)
 ${!courses[@]}  It returns all indexes where elements are available.
 ${#courses[@]} It returns the number of elements present inside array.
 ${#courses[0]}  It returns the length of first element.

Write a Script to print all above types of access specifier array:


O/P:

Note:

1) If we create an array with elements directly

fruits=("Apple" "Orange" "Banana" "Mango")

then the indices will be 0,1,2,3 etc

2) After creating array we can add extra elements also

fruits=("Apple" "Orange" "Banana" "Mango")

fruits[4]="Sapota"

Q]Is it Possible to Remove Array Elements?

Yes possible by using unset command.


O/P:

Shell Script Functions


If any group of commands are repeatedly required, then it is not recommended to write these
commands separately every time. It increases length of the code and reduces readability.

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:

 It reduces length of the code.


 It improves readability.
 It improves maintainability.
 It promotes DRY principle.
 DRY  Don't Repeat Yourself.

How to define a Function?

1st Way:

function function_name()

commands

2nd Way:

function_name()

{
commands

Q]Write a Function to Display wish Message?

O/P:

Function with Parameters:


Function can accept parameters also. With in the function, we can access parameters as follows:

 $1 First Parameter
 $2 Second Parameter
 $@ All Paramters
 $* All parameters
 $# Total number of parameters
 $0  It is script name but not function name

Q]Write a Function to demonstrate how to access Function Parameters?


O/P:

Q] Write a Function to find Maximum of 2 given Integer Numbers?

O/P:

You might also like