What is shell scripting?
Shell Scripting is a program to write a series of commands for the shell to execute or simply we can say that shell scripting is writing a bunch of command and executing them from shell itself.
Shell: A shell is a computer program that presents a command line interface which allows you to control your computer using commands entered with a keyboard instead of controlling graphical user interfaces (GUIs) with a mouse/keyboard/touchscreen combination.
Script: A script is a program or sequence of instructions that is interpreted or carried out by another program.
Type of Shells:
Depending on different OS there are different type of shells. To check type of shells offered by your OS just type:
cat /ect/shells
To check path of your Shell
which bash
Bash: Bourne-Again Shell
Dash: Debian Almquist shell
rbash: If Bash is started with the name rbash , or the --restricted or -r option is supplied at invocation, the shell becomes restricted
. A restricted shell is used to set up an environment more controlled than the standard shell.
Let's make our first shell script
Just open your Terminal and follow the steps:
Simply type in terminal:
touch hello.sh
Now, open this file with any editor here I am using VsCode but you can use any IDE according to your preference.
Now, from here we will be writing the commands in our hello.sh file.
- before starting with your shell script file always specify the path of your shell (in my case I am using bash so I am specifying bash path followed by
#!
)
Printing Hello-World using hello.sh
#! /bin/bash
- declaring comments using
#
# it is a comment
- printing hello-world using
echo "Hello-World"
Now save the changes in hello.sh script
#! /bin/bash # it is a comment echo "Hello-World"
and run the script file in terminal using
./hello.sh
System defined variables
- Build-in or system defined variables will always be in Capital letters i.e
BASH, HOME
and variables will always be called after$
echo Our shell is: $BASH #give bash shell name echo Our shell version is: $BASH_VERSION echo Our home directory is: $HOME echo Our current working directory is: $PWD
Declaring global variables
NOTE:
there variables can be called globallyname=Mark echo The name is: $name value=10 echo The value is: $value
Taking input from user for variables
echo "Enter names: " read n1 n2 n3 n4 echo "Names: $n1,$n2,$n3,$n4"
Taking silent input and in same line
-p
for taking input in same line-s
for taking silent input i.e data will not be visible while insertingread -p "username: " u_name read -sp "password: " pass echo echo "username: $u_name" echo "password: $pass"
Declaring arrays
-a
for array@
for printing all values of arrayecho "Enter names: " read -a name echo Names are : ${name[@]}
- Printing specific values of array
echo "Enter names: " read -a name echo "Names are : ${name[0]}, ${name[1]}"
Printing index of array
echo "Enter names: " read -a name echo Index of array : ${!name[@]}
Printing length of array
echo "Enter names: " read -a name echo Length of array is : ${#name[@]}
Adding values to array
os=('ubuntu' 'windows' 'mac') os[3]='kali' #--> setting value echo Array is : ${os[@]}
- Removing values from array
os=('ubuntu' 'windows' 'mac') unset os[2] #--> remove value from 2nd index os[3]='kali' #--> setting value echo Array is : ${os[@]}
Reading input by default variable
- By default data value will be stored in a default variable
REPLY
echo "Enter name: " read echo "Name is : $REPLY"
Taking input as argument
echo Names are : $1 $2 $3
Alternate method
args=("$@") #arguments as an array echo Names are : $@
if statement
-ne
for not equal comparisonfi
for telling system that if statement ends here.count=10 if (( $count == 1 )) # or if [ $count -eq 10 ] then echo "equal" elif [ $count -ne 1 ] then echo "not equal" else echo "Invalid" fi #--> to specify end of if statement
Here is the list of specifying operators in shell scripting
File/Folder test operators
- Before executing the below code make sure that you have created some files/folders.
-e
for taking input in same line-f
for checking there is file or not-w
for checking write permissionscat >>
for inserting and appending data.
In my case I have a file as hiecho -e "Enter the name of the file : \c" read file_name if [ -e $file_name ] # -e for exist or not # -f for it is file or not # -d for it is directory or not # -s for file is empty or not then echo "$file_name found" else echo "$file_name not found" fi
Inserting/Appending data to file
Before moving ahead you have to make sure that you have a file to enter some data and the file mush have write permissions. To check write permissions just typeecho -e "Enter the name of the file : \c" read file_name if [ -f $file_name ] then if [ -w $file_name ] then echo "type some text data. Press ctrl+d to exit." cat >> $file_name else echo "File don't have write permissions." fi else echo "$file_name not found" fi
ls -la
If your file don't have any write permissions to that file just typechmod +w <file_name>
Now executing the bash file Even if you try to add text again the text will not be overwritten rather it will be appended to the file
switch case
pattern based caseecho Hey choose an option echo echo a=To see current date echo b=list all the files in current dir echo -e "Enter choice : \c" read choice case $choice in a) date;; b) ls;; *) echo "Invalid output" esac #--> specifying end of switch case
echo -e "Enter some character : \c" read value case $value in [a-z] ) echo "a-z";; [A-Z] ) echo "A-Z";; [0-9] ) echo "0-9";; ? ) echo "specical char";; * ) echo "invalid" esac
for loop
- Method 1
Method 2for i in 1 2 3 4 5 do echo the number is $i done
Method 3for j in eat your lunch do echo $j done
Method 4for p in {1..10..2} # {start..end..increment}--> not work in version less than 4 do echo $p done
for loop to execute commandfor (( i-0; i<5; i++ )) do echo $i done
printing folders from for loopfor command in ls pwd date do echo -------------$command------------ #--->printing command $command # --->running command done
iterating values from file ;for i in * do if [ -d $i ] #---> -d for folders and -f for files then echo $i fi done
hosts
is the path of file includingfile_name
at last i.e where I have writtenhi
hosts="/home/shankar/Desktop/shell_script/hi" for i in $(cat $hosts) do echo $i done
while loop
count=0 num=10 while [ $count -le $num ] # ---> -le for less than equal to do echo Numbers are $count let count++ done
select loop
select name in mark john ben julie do case $name in mark ) echo "mark selected" ;; john ) echo "john selected" ;; ben ) echo "ben selected" ;; julie ) echo "julie selected" ;; * ) echo "invalid" ;; esac done
until loop
n=0 until [ $n -ge 10 ] do echo $n n=$(( n+1 )) ## or let n++ done
Logical Operators
- AND operator
-gt
for greater than-lt
for less than&&
or-a
for AND logical operator
OR operatora=6 if [ $a -gt 5 ] && [ $a -lt 7 ] then echo "true" else echo "false" fi
||
or-o
for OR logical operatora=1 if [ $a -gt 5 ] || [ $a -lt 7 ] then echo "true" else echo "false" fi
Arithmetic operators
floating point operationsa=20 b=10 echo $(( a+b )) echo $(expr $a - $b ) #-->alternate way echo $(( a/b )) echo $(( a*b )) echo $(( a%b ))
bc
for basic calculation in floatscale
is the number of values after decimal point-l
for calling math libraryn=2.5 m=4.4 echo "$n+$m" | bc echo "$n-$m" | bc echo "$n*$m" | bc echo "scale=2;$m/$n" | bc echo "$m%$n" | bc num=4 echo "scale=2;sqrt($num)" | bc -l #--> -l for calling math library echo "3^3" | bc -l
Reading a file's content
- Put file name in place of
hi
Method 1
Method 2while read p do echo $p done < hi
Method 3cat hi | while read p do echo $p done
-r
for mentioning end of linewhile IFS=' ' read -r line do echo $line done < hi
Functions
- Method 1
Method 2function greet(){ echo "Hello-World" } greet # --> calling function
name(){ echo $1 } name Ram # --> calling function
Declaring local variables
- while declaring function the variable we use are global i.e can be used outside the function but sometime we don't want such behavior so we define local variables followed by
local
keyword.id(){ local name=$1 echo $name } name=Ram echo names is $name before id Ben echo names is $name after
Declaring readonly variables
- after making variables readonly you would not be able to change its value
var=31 readonly var var=50 echo var is : $var
Declaring readonly functions
- after making function readonly we will not be able to overwrite this function
hello(){ echo Hello guys } readonly -f hello #--> -f for function hello
Signal and Trap
trap "echo file deleted" 0 2 15 echo "pid is $$" while (( COUNT < 10 )) do sleep 1 (( COUNT ++ )) echo $COUNT done exit 0
Debugging
- Method 1
Method 2bash -x ./hello.sh
set -x #--> from echo hi #--> script set +x #--> to
That's it You are now done with shell scripting. Hope the above information was valuable to you.