Hello World
Hello World
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. 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. Check
the below bash script example.
#!/bin/bash
((sum=25+35))
#Print the result
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.
#!/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
else
fi
The AND operator is denoted by the && sign.
#!/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.
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
#!/bin/bash
do
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
#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"
21. Functions in Bash
As with any programming dialect, functions play an essential role in Linux shell scripts. They allow admins to create
custom code blocks for frequent usage. The below demonstration will outline how functions work in Linux bash scripts.
#!/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=”[email protected]”
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`
echo "Current Date is: $day-$month-$year"
#!/bin/bash
read time
sleep $time
#!/bin/bash
sleep 5 &
pid=$!
kill $pid
wait $pid
#!/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
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.
39. Removing Duplicate Lines from Files
File processing takes considerable time and hampers the productivity of admins in many ways. Searching for duplicates in
your files can become a daunting task. Luckily, you can do this with a short shell script.
#! /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
Ending Thoughts
Linux shell scripts can be as diverse as you can imagine. There’s literally no limit when it comes to determining what it
can do or can’t. If you’re a new Linux enthusiast, we highly recommend you to master these fundamental bash script
examples. You should tweak them to understand how they work more clearly. We’ve tried our best to provide you with all
the essential insights needed for modern Linux bash scripts. We’ve not touched on some technical matters due to the sake
of simplicity. However, this guide should prove to be a great starting point for many of you.