September 27, 2024 12:55 pm
Topic starter
Notifications
Clear all
0
important dollar notations used in shell scripts:
-------------------------------------------------------
$# --> To know number of arguments passed to script
$$ --> To know PID(processID) of the script
$* --> To print all arguments name passed to script
$0 --> To Print the name of script which i am executing
#!/bin/bash
echo "Display employee name $1 "
echo "Display emloyee id $2 "
echo "Display employee location $3 "
echo "Display employee state $4 "
echo
echo " number of arguments passed to script is ==> $# "
echo " PID(processID) of the script is ==> $$ "
echo " print all arguments i have passed to this script ==> $* "
echo " Print the name of script which i am executing ==> $0 "
Conditional statements:
-----------------------
The conditional statement is used to do some activity based on decision-making (i.e true / false).
if else condition:
------------------
syntax:
if [ <condition> ]
then
#commands to be executed if condition is true
else
#commands to be executed if we condition is flase
fi
=====================================
-------------------------------------------------------------------------------------------------
script to check whether given string is alice or not using 3 VARIABLE SUBSTITUTION formats?
==========================================================================================
ex: Script in hardcoded format
#!/bin/bash
MYNAME=alice
if [ $MYNAME = "alice" ]
then
echo "Condition is true, Hello alice Good morning "
else
echo "username entered is not alice.... PLease check again...."
fi
ex: Script in command line arguments format
#!/bin/bash
MYNAME=$1
if [ $MYNAME = "alice" ]
then
echo "Condition is true, Hello alice Good morning "
else
echo "username entered is not alice.... PLease check again...."
fi
observations:
if we pass alice as argument ($1) alice = alice ===> condition true ==> execute command under then
if we pass viratkohli as argument ($1) viratkohli = alice ==> condition false ==> execute command under else
ex: Script in read command format
#!/bin/bash
echo "enter value for variable named MYNAME ....."
read MYNAME
if [ $MYNAME = "alice" ]
then
echo "Condition is true, Hello alice Good morning "
else
echo "username entered is not alice.... PLease check again...."
fi
script to check that whether argument passed to script is 5 or not?
-------------------------------------------------------------------
#!/bin/bash
value1=$1
if [ $value1 = 5 ]
then
echo " Condition is true, value is 5 "
else
echo " Condition is fasle, value is incorrect & it is not 5 "
fi
=========================================================================================
Relational Operators: (Numeric Comparison Operators)
-----------------------------------------------------
These operators are used to evaluate mathematical conditions in if condition of shell script
-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)
true --> block inside then block will get executed
false --> block inside else block will get executed
1. script to check given number ( as argument) is equal to 10 or not ?
test.sh
-------
#!/bin/bash
if [ $1 -eq 10 ]
then
echo " condition is true/ sucesss: Given argument value is 10.... "
else
echo "condition has failed : Given argument value is not 10.... "
fi
------------
2. script to check given number is greater than 5 or not.
#!/bin/bash
if [ $1 -gt 10 ]
then
echo " condition is true/ sucesss: Given argument value is greater 10.... "
else
echo "condition has failed : Given argument value is lesser than 10.... "
fi
-----------
3. script to check only two arguments are passed to script ?
Note: $# --> command to check number of arguments parsed to script
#!/bin/bash
if [ $# -eq 2 ]
then
echo " condition is true/ sucesss: Arguments passed to script is 2 "
else
echo "condition has failed: Arguments passed to script are not 2 "
fi
Note:
-----
#(comment) ==> if a line starts with # its considered as comment & it will get ignored while executing script.
comment is generally used for authors refernce
shell scripting is also called bash scripting
Note:
-------
ALL possible conditions which can be used with "if conditions"
a.conditions used for matching / checking "strings" are :
eg: string => alice = junjesh
[ $STRING == STRING ] - Equal
[ $STRING != STRING ] - Not Equal
b. conditions used for "mathematicall operations" / Relational operators are :
here NUM means number
[ $NUM -eq NUM ] - Equal
[ $NUM -ne NUM ] - Not equal
[ $NUM -lt NUM ] - Less than
[ $NUM -le NUM ] - Less than or equal
[ $NUM -gt NUM ] - Greaterthan
[ $NUM -ge NUM ] - Greater
c. conditions used for checking file/directory/ link types are:
[ -f $FILE ] - Exists ==> to check file Exists are not
[ -d $DIRECTORY ] - Directory ==> to check directory Exists are not
[ -h $FILE ] - Symlink/softlink ==> to check link is softlik are not
To check permissions of file:
[ -r $FILE ] - Readable ==> to check file has read permissions are not
[ -w $FILE ] - Writable ==> to check file has write permissions are not
d. based on commands exit status :
[ $? -eq 0 ] # conditions used, if previous commans return zero/ non zero exit code
If $? equals zero, it indicates success.
If $? is non-zero, it indicates failure.
examples on if conditions used for checking file/directory/ link types are:
--------------------------------------------------------------------------------
#check the file exists/ are not in the given name (as input from read command)
Note:
----
[ -f $FILENAME ] ==> this condition block used to check FILE in mentioned name exists or not ?
[ -d $DIRECTORYNAME ] ==> condition block used to check directory in mentioned name exists or not
[ -h $FILENAME ] ==> this condition block used to check hardlink in mentioned name exists or not ?
script to check the file exists/ are not in the given name (as input from read command):
-------------------------------------------------------------------------------------
[ec2-user@ip-172-31-24-167 ~]$ cat if_check_for_fileName.sh
#!/bin/bash
echo " Enter input file name you need to check............"
read FILE_NAME
if [ -f $FILE_NAME ]
then
echo " file name provided by you in read command is available in pwd & please find its details below....."
echo"$FILE_NAME"
else
echo " file name provided in read command is unavailable/doesent exist....."
fi
Script to check the directory exists/ are not in the given name (as input from read command) :
----------------------------------------------------------------------------------------------
[ec2-user@ip-172-31-24-167 ~]$ cat if_check_for_directoryName.sh
#!/bin/bash
echo " Enter input directory name you need to check............"
read DIR_NAME
if [ -d $DIR_NAME ]
then
echo " Directory name provided by you in read command is available & please find its details below....."
echo "$DIR_NAME"
else
echo " Directory name provided in read command is unavailable/doesent exist....."
fi
Realtime script:
----------------
Note:
-----
in server hardware resources will be monitored (hardwares==> RAM, HDD, CPU)
for optimal performance of your application :
disk utilization ==> should be below 70%-80%
Ram ==> should be below 60%
Step1: extract the value of disk usage value (in numbers) using below series of command
[ec2-user@ip-172-31-11-142 ~]$
[ec2-user@ip-172-31-11-142 ~]$ df -kh
Filesystem Size Used Avail Use% Mounted on
devtmpfs 474M 0 474M 0% /dev
tmpfs 483M 0 483M 0% /dev/shm
tmpfs 483M 408K 482M 1% /run
tmpfs 483M 0 483M 0% /sys/fs/cgroup
/dev/xvda1 8.0G 1.6G 6.4G 20% /
tmpfs 97M 0 97M 0% /run/user/1000
[ec2-user@ip-172-31-11-142 ~]$
[ec2-user@ip-172-31-11-142 ~]$
[ec2-user@ip-172-31-11-142 ~]$
[ec2-user@ip-172-31-11-142 ~]$ df -kh | tail -2 | head -1
/dev/xvda1 8.0G 1. 6G 6.4G 20% /
[ec2-user@ip-172-31-11-142 ~]$
[ec2-user@ip-172-31-11-142 ~]$
[ec2-user@ip-172-31-11-142 ~]$ df -kh | tail -2 | head -1 | awk -F " " '{print$5}'
20%
[ec2-user@ip-172-31-11-142 ~]$
[ec2-user@ip-172-31-11-142 ~]$
[ec2-user@ip-172-31-11-142 ~]$ df -kh | tail -2 | head -1 | awk -F " " '{print$5}' | sed 's/%//g'
20
[ec2-user@ip-172-31-11-142 ~]$
[ec2-user@ip-172-31-11-142 ~]$
assign the extracted value (20) to a varaible DISK_USAGE as shown below
[ec2-user@ip-172-31-11-142 ~]$
[ec2-user@ip-172-31-11-142 ~]$ DISK_USAGE=`df -kh | tail -2 | head -1 | awk -F " " '{print$5}' | sed 's/%//g'`
[ec2-user@ip-172-31-11-142 ~]$
[ec2-user@ip-172-31-11-142 ~]$
[ec2-user@ip-172-31-11-142 ~]$ echo $DISK_USAGE
20
[ec2-user@ip-172-31-11-142 ~]$
step3: using above varaible write a script which will check if disk usage is more than 70%, to do some cleanup activity
vi disk_check_script.sh
------------------------
#!/bin/bash
DISK_USAGE=`df -kh | tail -2 | head -1 | awk -F " " '{print$5}' | sed 's/%//g'`
if [ $DISK_USAGE -gt 70 ]
then
echo " take action & delete some files ....."
sudo rm -f /tmp/*
sudo rm -rf /opt/logs/*
#mail -s "disk utilasation has gone beyond 70%" ajey@xyz.com teamlead@xyz.com
else
echo "since disk usage is less than 70 , we are good...."
fi
Note:
-----
How do you run script in background?
-------------------------------------
add & (ampercend) at the end of script while executing
syntax: sh <myscript>.sh &
##Mutiple conditios checks____
----------------------------
if [ condition ]
then
echo "statment"
elif [ condition ]
then
echo "statment"
else
echo "statement"
fi
------------
#shell script to find the greatest of three numbers
echo "Enter Num1"
read num1
echo "Enter Num2"
read num2
echo "Enter Num3"
read num3
if [ $num1 -gt $num2 ] && [ $num1 -gt $num3 ]
then
echo $num1
elif [ $num2 -gt $num1 ] && [ $num2 -gt $num3 ]
then
echo $num2
else
echo $num3
fi
-----------------------
Loops
----------
shell scripts can repeat particular instruction again and again, until particular condition satisfies.
A group of instruction that is executed repeatedly is called a loop.
why loops?
If we want to execute a group of commands multiple times then we should go for loops / iterative statements.
Types of loops
Majorly we have two types of loops
• For loop
• While loop
For Loop
------------
for loop operates on lists of items. It repeats a set of commands for every item in a list.
The for loop syntax:
for var in item1 item2 ... itemN
do
command1
command2
....
...
commandN
done
eg1: Script to Print welcome 5 times using for loop
#!/bin/bash
for i in 1 2 3 4 5
do
echo "Welcome $i times."
done
output
--------
Welcome 1 times
Welcome 2 times
welcome 3 timess
Welcome 4 times
Welcome 5 times
------------------------
eg2_for loop:
---------------
script to print variable values & create directory for each value........
#!/bin/bash
set -x
for my_dir in dir_1 dir_2 dir_4 dir_3
do
echo " create directory for each tool in my_dir "
mkdir $my_dir
ls -lrt | tail -1
echo
echo
echo
done
echo " closing script execution........"
-----------------------
eg3_for loop:
---------------
script to print variable values & create directory for each value........
#!/bin/bash
set -x
for TOOL_STACK in git jenkins docker k8s aws ansible
do
echo " Currently we are learning this $TOOL_STACK "
echo " create directory for each tool in Tool stack "
mkdir $TOOL_STACK
ls -lrt | tail -1
echo
echo
echo
done
echo " closing script execution........"
eg3 for loop : to scp files to multiple servers
-----------------------------------------------------
#!/bin/bash
set -x
for servers in { server1, server2, server3, server4 }
do
scp myfile1 ec2-user@$servers:/home/ec2-user
done
___________________________________________________________________________________________________________________________________
While Loop
-------------
The while statement is used to executes a list of commands repeatedly until condition gets sattisfied.
syntax::
---------
intiatilization
while [ condition ]
do
command1
command2
....
...
commandN
<increment / decrement>
done
Script to Print welcome 5 times using while loop...... < to get detailed ouput >
-----------------------------------------------------------------------------------
#!/bin/bash
set -x
i=0
while [ $i -le 5 ]
do
echo " i value at begging of itteration is: $i "
echo "welcome $i time"
i=`expr $i + 1`
echo " i value at end of itteration is $i "
echo
echo "----------- < ending this itterartion>-------------"
echo
done
ouput:
---------
welcome 0 time
welcome 1 time
welcome 2 time
welcome 3 time
welcome 4 time
welcome 5 time