Bash shell Scripting
Basic Shell Scripts:
Output to screen
#!/bin/bash
# Simple output script
echo "Hello World"
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’
echo "My first name is $a"
echo "My surname is $b"
echo ‘My surname is $c’
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
Scripts to run commands within
#!/bin/bash
# Script to run commands within
clear
echo "Hello `whoami`"
echo
echo "Today is `date`"
echo
echo "Number of user login: `who | wc -l `"
echo
Read input and perform a task
#!/bin/bash
# This script will rename a file
echo Enter the file name to be renamed
read oldfilename
echo Enter the new file name
read newfilename
mv $oldfilename $newfilename
echo The file has been renamed as $newfilename
IF Statements
If-then Scripts:
Check the variable
#!/bin/bash
count=100
if [ $count -eq 100 ]
then
echo Count is 100
else
echo Count is not 100
fi
Check if a file error.txt exist
#!/bin/bash
clear
if [ -e /home/ubuntu/error.txt]
then
echo "File exist"
else
echo "File does not exist"
fi
Check if a variable value is met
#!/bin/bash
a=`date | awk '{print $1}'`
if [ "$a" == Mon ]
then
echo Today is $a
else
echo Today is not Monday
fi
Check the response from the prompt and then output
#!/bin/bash
clear
echo
echo "What is your name?"
echo
read a
echo
echo Hello $a sir
echo
echo "Do you like working in IT? (y/n)"
read Like
echo
if [ "$Like" == y]
then
echo You are cool
elif [ "$Like" == n]
then
echo You should try IT, it’s a good field
echo
fi
Other If statements
If the output is either Monday or Tuesday
if [ “$a” = Monday ] || [ “$a” = Tuesday ]
Test if the error.txt file exist and its size is greater than zero
if test -s error.txt
if [ $? -eq 0 ] If input is equal to zero (0)
if [ -e /export/home/filename ] If file is there
if [ "$a" != "" ] If variable does not match
if [ error_code != "0" ] If file not equal to zero (0)
Comparisons:
-eq equal to for numbers
== equal to for letters
-ne not equal to
!== not equal to for letters
-lt less than
-le less than or equal to
-gt greater than
-ge greater than or equal to
File Operations:
-s file exists and is not empty
-f file exists and is not a directory
-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 'a = Display Date and Time'
echo 'b = List file and directories'
echo 'c = List users logged in'
echo 'd = Check System uptime'
echo
read choices
case $choices in
a) date;;
b) ls;;
c) who;;
d) uptime;;
*) echo Invalid choice - Bye.
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
echo "Welcone $c times"
(( c++ ))
done
Script to run for a number of seconds
#!/bin/bash
count=0
num=10
while [ $count -lt 10 ]
do
echo
echo $num seconds left to stop this process $1
echo
sleep 1
num=`expr $num - 1`
count=`expr $count + 1`
done
echo
echo $1 process is stopped!!!
echo
for loop Scripts:
Simple for loop output
#!/bin/bash
for i in 1 2 3 4 5
do
echo "Welcome $i times"
done
Simple for loop output
#!/bin/bash
for i in eat run jump play
do
echo See Imran $i
done
for loop to create 5 files named 1-5
#!/bin/bash
for i in {1..5}
do
touch $i
done
for loop to delete 5 files named 1-5
#!/bin/bash
for i in {1..5}
do
rm $i
done
Specify days in for loop
#!/bin/bash
i=1
for day in Mon Tue Wed Thu Fri
do
echo "Weekday $((i++)) : $day"
done
List all users one by one from /etc/passwd file
#!/bin/bash
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
2. Change the IP to 192.168.1.235
Don't show the output
ping -c1 192.168.1.1 &> /dev/null
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
3. Change the IP to 192.168.1.235
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
Deleting of Old files
Create files with older timestamp
touch -d "Thu, 1 March 2018 12:30:00" a
Find and delete files older than 90 days
find /path-to-dir -mtime +90 -exec ls -l {} \;
Find and rename old files
find . -mtime +90 -exec mv {} {}.old \;
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
For loops Scripts for File System - 1
==========================================
1 - Simple counting:
#!/bin/bash
for i in {1..25}
do
sleep 1
echo $i
done
-------------------------------------------------
2 - Create multiple files with different names
#!/bin/bash
for i in {1..10}
do
touch vinay.$i
done
--------------------------------------------------
3 - Create multiple files upon input
#!/bin/bash
echo How many files do you want?
read t
echo
echo Files names should start with?
read n
for i in $(seq 1 $t)
do
touch $n.$i
done
--------------------------------------------------
4 - Assign write permissions to files
#!/bin/bash
for i in vinay*
do
echo Assigning write permissions to $i
chmod a+w $i
sleep 1
done
-------------------------------------------------
5 - Assign write permissions to files with total time it will take
#!/bin/bash
total=`ls -l vinay* | wc -l`
echo It will take $total seconds to assign permissions...
echo
for i in vinay*
do
echo Assigning write permissions to $i
chmod a+w $i
sleep 1
done
For loops Scripts for File System - 2
1 - Rename all *.txt files extension to none
#!/bin/bash
for filename in *.txt
do
mv $filename ${filename%.txt}.none
done
---------------------------------------------------------------------
2 - Check to see if files exist
#!/bin/bash
# List of files you are curious about
FILES="/etc/passwd
/etc/group
/etc/shadow
/etc/nsswitch.conf
/etc/sshd_ssh_config
/etc/fake"
echo
for file in $FILES
do
if [ ! -e "$file" ] # -e is an option for Check if file exists.
then
echo $file = does not exist
echo
fi
done
Copying a file to a list of remote hosts
==============================================
#!/bin/bash
for HOST in ubuntu01 fedora02 centos03 rhel06
do
scp somefile $HOST:/var/tmp/
done
Check if the directories in /home are assigned to a user
=========================================================
Become root
vi checkdir
cd /home
mkdir junos
#!/bin/bash
cd /home
for DIR in *
do
CHK=$(grep -c "/home/$DIR" /etc/passwd)
if [ $CHK -ge 1 ]
then
echo "$DIR is assigned to a user"
else
echo "$DIR is NOT assigned to a user"
fi
done
List of Users Logged in Today
================================
#!/bin/bash
today=`date | awk '{print $1,$2,$3}'`
#last | grep $today | awk '{print $1}'
last | grep "$today"
-------------------------------------------------------------
Ask for Input
#!/bin/bash
echo "please enter day (e.g. Mon)"
read d
echo "please enter month (e.g. Aug)"
read m
echo "please enter date (e.g. 28)"
read da
last | grep "$d $m $da"