Shell Scripting
Shell Scripting
Uttam Kiran
Why Shell scripts
Many More
Kernel And Shell
1. What is Kernel
2. What is Shell
3. Types of shells
4. Starting a Shell
5. How to run a shell script
Kernel & Shell
software
# echo $0
Shell Script & Type of Shells
Keeping all the instructions in a file and execute them with mentioned shell.
Linux provide you Command line OS the user to perform the operations on hardware.
#!/bin/bash
ls
A variable is a character string to which we assign a value. The value assigned could be a number, text, filename,
device, or any other type of data.
Input/Output
read
echo
if-then scripts
if-then statements
Otherwise = do that
#!/bin/bash
read count
echo $count
clear
file=`pwd`/error.txt
echo $file
if [ -e $file ]
then
else
.Case
#!/bin/bash
read choices
case $choices in
a) date;;
b) ls;;
For loop scripts
For loop
#!/bin/bash
Keep running the scripts until
for i in 1 2 3 4
specified no of variable do
echo "The value is $i"
Eg: variable=10 run the script 10 times Done
—-----------------------------
#!/bin/bash
for i in {1..5}
do
touch $i
done
do…while
#!/bin/bash
The while condition continuously executes
count=0
A block of statement while a particular condition while [ $count -lt 10 ]
do
is true or false echo $count
count=`expr $count + 1`
count = $[$count +1 ]
while [ condition ] done
echo Done
do —-------------------------------------------------------------
#!/bin/bash
Condition 1 count=0
num=10
while [ $count -lt 10 ]
Condition 2 do
echo
done echo $num seconds left to stop this process $1
echo
Exit Status
0 - OK or Successful
1 - minor problem
echo $?
1 - indicates that a container shut down, either because of an application failure or because the image pointed to an
invalid file (cat asdasdasd 000 )
Use of awk → format the output of the script | awk ‘{$print $1}’ | wc -l
Script for server Connectivity
#!/bin/bash hosts=172.31.81.34
hosts="/home/ubuntu/prof-s ping -c1 $hosts &> /dev/null
cripts/hosts" if [ $? -eq 0 ]
for ip in $(cat $hosts) then
do echo $hosts is OK
ping -c1 $ip &> /dev/null else
if [ $? -eq 0 ] echo $hosts Not OK
then fi
echo $ip is OK
else
echo $ip Not OK
fi
Script for server Connectivity
Create a hosts file in the present directory and save all IPs in the file.
crontab -e
# find <directory_path> -mtime +90 -exec ls -l {} \; —> to find 90 days old files.
# find <directory_path> -mtime +90 -exec mv {} {}.old \; → rename 90 days old files