Linux Shell Script Examples
Linux Shell Script Examples
Historically, the shell has been the native command-line interpreter for Unix-
like systems. It has proven to be one of Unix’s major features throughout the
years and grew into a whole new topic itself. Linux offers a variety of powerful
shells with robust functionality, including Bash, Zsh, Tcsh, and Ksh. One of the
most amazing features of these shells is their programmability. Creating
simple yet effective Linux shell scripts for tackling day-to-day jobs is quite
easy. Moreover, a modest knowledge of this topic will make you a Linux
power user in no time. Stay with us to for a detailed introduction to Unix shell
scripting.
The majority of shell scripting done on Linux involve the bash shell. However,
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. However, our editors have
also tried to outline some shell script examples that deal with shells other than
bash. As a result, you’ll find a substantial amount of familiarity between
different shell scripts.
Bash, aka the Bourne Again Shell, is the default command-line interpreter in
most Linux distros nowadays. It is an upgrade of the earlier Bourne shell that
was first introduced in Version 7 Unix. Learning bash shell scripting will allow
you to understand other shell scripts much faster. So, try these simple
examples yourself to gain the first-hand experience.
1. Hello World
Programmers often learn new languages via learning the hello world program.
It’s a simple program that prints the string “Hello World” to the standard
output. Then, use an editor like vim or nano to create the file hello-world.sh
and copy the below lines into it.
#!/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
3. Using Comments
Comments are useful for documentation and are a requirement for high-
quality codebases. It’s a common practice to put comments inside codes that
deal with critical logic. To comment out a line, just use the #(hash) character
before it. For example, check the below bash script example.
#!/bin/bash
# Adding two values
((sum=25+35))
echo $sum
This script will output the number 60. First, 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 is 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. In addition, the [[ ]] are
required.
#!/bin/bash
read n
if [ $n -lt 10 ];
then
else
#!/bin/bash
read num
else
fi
The AND operator is denoted by the && sign.
11. Using the OR Operator
The OR operator is another crucial construct that allows us to implement
complex, robust programming logic in our scripts. Contrary to AND, a
statement consisting of the OR operator returns true when either one of its
operands is true. It returns false only when each operand separated by the
OR is false.
#!/bin/bash
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.
#!/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.
Instead, 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
#!/bin/bash
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.
#!/bin/bash
string1="Ubuntu"
string2="Pit"
string=$string1$string2
echo "$string is a great resource for Linux beginners."
The following program outputs the string “UbuntuPit is a great resource for
Linux beginners.” to the screen.
#!/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
#subStr=${Str:0:20}
echo $subStr
Check out this guide to understand how Linux Cut command works.
19. Adding Two Values
It’s quite easy to perform arithmetic operations inside Linux shell scripts. The
below example demonstrates how to receive two numbers as input from the
user and add them.
#!/bin/bash
read x
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
This script simply calls your standard shell command mkdir and passes it the
directory name if you look closely. 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.
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
#!/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.
#!/bin/bash
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”
`mail -s $subject $recipient <<< $message`
It will send an email to the recipient containing the given subject and
message.
#!/bin/bash
year=`date +%Y`
month=`date +%m`
day=`date +%d`
hour=`date +%H`
minute=`date +%M`
second=`date +%S`
echo `date`
read time
sleep $time
#!/bin/bash
sleep 5 &
pid=$!
kill $pid
wait $pid
#!/bin/bash
ls -lrt | grep ^- | awk 'END{print $NF}'
For the sake of simplicity, we’ll avoid describing how awk functions in this
example. Instead, you can simply copy this code to get the task done.
#!/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
exit 1
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.
#!/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
echo -e "\n$(date "+%d-%m-%Y --- %T") --- Starting
work\n"
apt-get update
apt-get -y upgrade
apt-get -y autoremove
apt-get autoclean