Bash Shell Scripting
Bash Shell Scripting
Defining Tasks
#!/bin/bash
# Define small tasks
whoami
echo
pwd
echo
hostname
echo
ls -ltr
echo
Defining variables
#!/bin/bash
# Example of defining variables
a=vinay
b=prasad
c=’Linux class’
Read Input
#!/bin/bash
# Read user input
echo "What is your first name?"
read a
echo
echo "What is your last name?"
read b
echo
echo Hello $a $b
#!/bin/bash
clear
echo "Hello `whoami`"
echo
echo
echo
read oldfilename
read newfilename
mv $oldfilename $newfilename
IF Statements
If-then Scripts:
Check the variable
#!/bin/bash
count=100
then
else
fi
clear
if [ -e /home/ubuntu/error.txt]
then
fi
if [ "$a" == Mon ]
then
echo Today is $a
else
fi
clear
echo
echo
read a
echo
echo
read Like
echo
if [ "$Like" == y]
then
elif [ "$Like" == n]
then
echo
fi
Other If statements
Test if the error.txt file exist and its size is greater than zero
if test -s error.txt
Comparisons:
-eq equal to for numbers
File Operations:
-s file exists and is not empty
-d directory exists
-x file is executable
-w file is writable
-r file is readable
case Scripts:
#!/bin/bash
echo
echo Please chose one of the options below
echo
echo
read choices
case $choices in
a) date;;
b) ls;;
c) who;;
d) uptime;;
esac
This script will look at your current day and tell you the state of the
backup
#!/bin/bash
NOW=$(date +"%a")
case $NOW in
Mon)
echo "Full backup";;
Tue|Wed|Thu|Fri)
echo "Partial backup";;
Sat|Sun)
echo "No backup";;
*) ;;
esac
do-while Script
Script to run for a number of times
#!/bin/bash
c=1
while [ $c -le 5 ]
do
done
#!/bin/bash
count=0
num=10
do
echo
echo
sleep 1
num=`expr $num - 1`
count=`expr $count + 1`
done
echo
echo
#!/bin/bash
for i in 1 2 3 4 5
do
#!/bin/bash
do
done
for i in {1..5}
do
touch $i
done
for i in {1..5}
do
rm $i
done
i=1
done
i=1
for username in `awk -F: '{print $1}' /etc/passwd`
do
echo "Username $((i++)) : $username"
done
Examples:
Checking the remote host connectivity
#!/bin/bash
ping -c1 192.168.1.1
if [ $? -eq 0 ]
then
echo OK
else
echo NOT OK
fi
3. Define variable
#!/bin/bash
hosts="192.168.1.1"
ping -c1 $hosts &> /dev/null
if [ $? -eq 0 ]
then
echo $hosts OK
else
echo $hosts NOT OK
fi
Multiple IPs
#!/bin/bash
IPLIST="path_to_the_Ip_list_file"
for ip in $(cat $IPLIST)
do
ping -c1 $ip &> /dev/null
if [ $? -eq 0 ]
then
echo $ip ping passed
else
echo $ip ping failed
fi
done
Backup
# Create backup
tar cvf /tmp/backup.tar /etc /var
# Compress backup
gzip backup.tar
#Check backup status and transfer
#!/bin/bash
tar cvf /tmp/backup.tar /etc /var
gzip backup.tar
find backup.tar.gz -mtime -1 -type f -print &> /dev/null
if [ $? -eq 0 ]
then
echo Backup was created
echo
echo Archiving backup
#scp /tmp/backup.tar.gz [email protected]:/path
else
echo Backup failed
fi