Keerthi Krishna - Linux Shell Script Examples
Keerthi Krishna - Linux Shell Script Examples
The majority of shell scripting done on Linux involve the bash shell. Power
users who have specified choices, often use other shells such as Zsh and
Ksh. We’ll mostly stick with Linux bash scripts in our examples due to
their widespread popularity and immense usability. Our editors have also
tried to outline some shell script examples that deal with shells other than
bash. You’ll find a substantial amount of familiarity between different
shell scripts.
#!/bin/bash
$ bash hello-world.sh
$ ./hello-world.sh
It will print out the string passed to echo inside the script.
Copy the below lines into a file called echo.sh and make it executable as
done above.
#!/bin/bash
#!/bin/bash
((sum=25+35))
echo $sum
This script will output the number 60. Check how comments are used
using # before some lines. The first line is an exception, though. It’s
called the shebang and lets the system know which interpreter to use
when running this script.
4. Multi-line comments
Many people use multi-line comments for documenting their shell scripts.
Check how this is done in the next script called comment.sh.
#!/bin/bash
: '
the square of 5.
'
((area=5*5))
echo $area
Notice how multi-line comments are placed inside :’ and ‘ characters.
#!/bin/bash
i=0
while [ $i -le 2 ]
do
echo Number: $i
((i++))
done
So, the while loop takes the below form.
while [ condition ]
do
commands 1
commands n
done
The space surrounding the square brackets are mandatory.
#!/bin/bash
do
done
printf "\n"
Save this code in a file named for.sh and run it using ./for.sh. Don’t forget
to make it executable. This program should print out the numbers 1 to 10.
#!/bin/bash
read something
8. The If Statement
If statements are the most common conditional construct available in
Unix shell scripting, they take the form shown below.
if CONDITION
then
STATEMENTS
fi
The statements are only executed given the CONDITION is true. The fi
keyword is used for marking the end of the if statement. A quick example
is shown below.
#!/bin/bash
read num
if [[ $num -gt 10 ]]
then
fi
The above program will only show the output if the number provided via
input is greater than ten. The -gt stands for greater than; similarly -lt for
less than; -le for less than equal; and -ge for greater than equal. The [[ ]]
are required.
9. More Control Using If Else
Combining the else construct with if allows much better control over your
script’s logic. A simple example is shown below.
#!/bin/bash
read n
if [ $n -lt 10 ];
then
else
fi
The else part needs to be placed after the action part of if and before fi.
#!/bin/bash
read num
if [[ ( $num -lt 10 ) && ( $num%2 -eq 0 ) ]]; then
else
fi
The AND operator is denoted by the && sign.
read n
if [[ ( $n -eq 15 || $n -eq 45 ) ]]
then
else
fi
This simple example demonstrates how the OR operator works in Linux
shell scripts. It declares the user as the winner only when he enters the
number 15 or 45. The || sign represents the OR operator.
12. Using Elif
The elif statement stands for else if and offers a convenient means for
implementing chain logic. Find out how elif works by assessing the
following example.
#!/bin/bash
read num
if [[ $num -gt 10 ]]
then
then
else
fi
The above program is self-explanatory, so we won’t dissect it line by line.
Change portions of the script like variable names and values to check how
they function together.
#!/bin/bash
read num
case $num in
100)
echo "Hundred!!" ;;
200)
*)
esac
The conditions are written between the case and esac keywords. The *) is
used for matching all inputs other than 100 and 200.
#!/bin/bash
do
case $index in
X) x=$val;;
Y) y=$val;;
*)
esac
done
((result=x+y))
echo "X+Y=$result"
Name this script test.sh and call it as shown below.
16. Concatenating Strings
String processing is of extreme importance to a wide range of modern
bash scripts. Thankfully, it is much more comfortable in bash and allows
for a far more precise, concise way to implement this. See the below
example for a quick glance into bash string concatenation.
#!/bin/bash
string1="Ubuntu"
string2="Pit"
string=$string1$string2
17. Slicing Strings
Contrary to many programming languages, bash doesn’t provide any in-
built function for cutting portions of a string. The below example
demonstrates how this can be done using parameter expansion.
#!/bin/bash
subStr=${Str:0:20}
echo $subStr
This script should print out “Learn Bash Commands” as its output. The
parameter expansion takes the form ${VAR_NAME:S:L}. Here, S
denotes starting position and L indicates the length.
#!/bin/bash
echo $subStr
Check out this guide to understand how Linux Cut command works.
#!/bin/bash
read y
(( sum=x+y ))
#!/bin/bash
sum=0
do
read n
(( sum+=n ))
done
printf "\n"
#!/bin/bash
function Add()
read x
read y
Add
Here we’ve added two numbers just like before. But here we’ve done the
work using a function called Add. So whenever you need to add again,
you can just call this function instead of writing that section again.
#!/bin/bash
function Greet() {
echo $str
read name
val=$(Greet)
#!/bin/bash
read newdir
cmd="mkdir $newdir"
eval $cmd
If you look closely, this script simply calls your standard shell command
mkdir and passes it the directory name. This program should create a
directory in your filesystem. You can also pass the command to execute
inside backticks(“) as shown below.
`mkdir $newdir`
#!/bin/bash
read dir
if [ -d "$dir" ]
then
else
`mkdir $dir`
fi
Write this program using eval to increase your bash scripting skills.
25. Reading Files
Bash scripts allow users to read files very effectively. The below example
will showcase how to read a file using shell scripts. Create a file called
editors.txt with the following contents.
1. Vim
2. Emacs
3. ed
4. nano
5. Code
This script will output each of the above 5 lines.
#!/bin/bash
file='editors.txt'
echo $line
26. Deleting Files
The following program will demonstrate how to delete a file within Linux
shell scripts. The program will first ask the user to provide the filename as
input and will delete it if it exists. The Linux rm command does the
deletion here.
#!/bin/bash
read name
rm -i $name
Let’s type in editors.txt as the filename and press y when asked for
confirmation. It should delete the file.
27. Appending to Files
The below shell script example will show you how to append data to a file
on your filesystem using bash scripts. It adds an additional line to the
earlier editors.txt file.
#!/bin/bash
cat editors.txt
cat editors.txt
You should notice by now that we’re using everyday terminal commands
directly from Linux bash scripts.
#!/bin/bash
filename=$1
if [ -f "$filename" ]; then
else
fi
We are passing the filename as the argument from the command-line
directly.
#!/bin/bash
recipient=”admin@example.com”
subject=”Greetings”
message=”Welcome to UbuntuPit”
#!/bin/bash
year=`date +%Y`
month=`date +%m`
day=`date +%d`
hour=`date +%H`
minute=`date +%M`
second=`date +%S`
echo `date`
#!/bin/bash
read time
sleep $time
#!/bin/bash
sleep 5 &
pid=$!
kill $pid
wait $pid
#!/bin/bash
#!/bin/bash
dir=$1
do
mv $file $file.UP
done
Firstly, do not try this script from any regular directory; instead, run this
from a test directory. Plus, you need to provide the directory name of
your files as a command-line argument. Use period(.) for the current
working directory.
#!/bin/bash
if [ -d "$@" ]; then
else
fi
The program will ask the user to try again if the specified directory isn’t
available or have permission issues.
#!/bin/bash
LOG_DIR=/var/log
cd $LOG_DIR
#!/bin/bash
BACKUPFILE=backup-$(date +%m-%d-%Y)
archive=${1:-$BACKUPFILE}
exit 0
It will print the names of the files and directories after the backup process
is successful.
The below example demonstrates a quick way to find out whether a user
is root or not from Linux bash scripts.
#!/bin/bash
ROOT_UID=0
then
else
fi
exit 0
The output of this script depends on the user running it. It will match the
root user based on the $UID.
#! /bin/sh
read filename
if [ -f "$filename" ]; then
else
fi
exit 0
The above script goes line by line through your file and removes any
duplicative line. It then places the new content into a new file and keeps
the original file intact.
40. System Maintenance
I often use a little Linux shell script to upgrade my system instead of
doing it manually. The below simple shell script will show you how to do
this.
#!/bin/bash
apt-get update
apt-get -y upgrade
apt-get -y autoremove
apt-get autoclean