30 Bash Script Examples
30 Bash Script Examples
30 Bash Script Examples
Bash scripts can be used for various purposes, such as executing a shell command, running
multiple commands together, customizing administrative tasks, performing task automation etc.
So knowledge of bash programming basics is important for every Linux user. This article will
help you to get the basic idea on bash programming. Most of the common operations of bash
scripting are explained with very simple examples here.
1. Hello World
2. Echo Command
3. Comments
4. Multi-line comment
5. While Loop
6. For Loop
7. Get User Input
8. If statement
9. And Condition if statement
10. Or Condition if statement
11. Else if and else condition
12. Case Condition
13. Get Arguments from Command Line
14. Get arguments from command line with names
15. Combine two strings in a variable
16. Get Substring of Strings
17. Add 2 numbers into a variable
18. Create a Function
19. Use Function Parameters
20. Pass Return Value from Script
21. Make directory
22. Make directory by checking existence
23. Read a file
24. Delete a File
25. Append to file
26. Test if File Exists
27. Send Email Example
28. Get Parse Current Date
29. Wait Command
30. Sleep Command
$ nano First.sh
Add the following bash script to the file and save the file.
#! /bin/bash
echo "Hello World"
You can run bash file by two ways. One way is by using bash command and another is by
setting execute permission to bash file and run the file. Both ways are shown here.
$ bash First.sh
Or,
You can use echo command with various options. Some useful options are mentioned in the
following example. When you use ‘echo’ command without any option then a newline is added
by default. ‘-n’ option is used to print any text without new line and ‘-e’ option is used to
remove backslash characters from the output. Create a new bash file with a name,
‘echo_example.sh’ and add the following script.
#! /bin/bash
echo "Printing text with newline"
2
echo -n "Printing text without newline"
echo -e "\n Removing \t backslash \t characters\n"
$ bash echo_example.sh
Use of comment:
‘#’ symbol is used to add single line comment in bash script. Create a new file named
‘comment_example.sh’ and add the following script with single line comment.
#! /bin/bash
$ bash comment_example.sh
You can use multi line comment in bash in various ways. A simple way is shown in the
following example. Create a new bash named, ‘multiline-comment.sh’ and add the following
script. Here, ‘:’ and “ ’ ” symbols are used to add multiline comment in bash script. This
following script will calculate the square of 5.
#! /bin/bash
:'
The following script calculates
the square value of the number, 5.
'
((area=5*5))
echo $area
3
Run the file with bash command.
$ bash multiline-comment.sh
You can check the following link to know more about the use of bash comment.
Create a bash file with the name, ‘while_example.sh’, to know the use of while loop. In the
example, while loop will iterate for 5 times. The value of count variable will increment by 1 in
each step. When the value of count variable will 5 then the while loop will terminate.
#! /bin/bash
valid=true
count=1
while [ $valid ]
do
echo $count
if [ $count -eq 5 ];
then
break
fi
((count++))
done
$ bash while_example.sh
You can check the following link to know more about the use of bash while loop.
The basic for loop declaration is shown in the following example. Create a file named
‘for_example.sh’ and add the following script using for loop. Here, for loop will iterate for 10
times and print all values of the variable, counter in single line.
#! /bin/bash
for (( counter=10; counter>0; counter-- ))
4
do
echo -n "$counter "
done
printf "\n"
$ bash for_example.sh
You can use for loop for different purposes and ways in your bash script. You can check the
following link to know more about the use of bash for loop.
‘read’ command is used to take input from user in bash. Create a file named ‘user_input.sh’
and add the following script for taking input from the user. Here, one string value will be taken
from the user and display the value by combining other string value.
#! /bin/bash
echo "Enter Your Name"
read name
echo "Welcome $name to LinuxHint"
$ bash user_input.sh
You can check the following link to know more about the use of bash user input.
Using if statement:
You can use if condition with single or multiple conditions. Starting and ending block of this
statement is define by ‘if’ and ‘fi’. Create a file named ‘simple_if.sh’ with the following script
to know the use if statement in bash. Here, 10 is assigned to the variable, n. if the value of $n
is less than 10 then the output will be “It is a one digit number”, otherwise the output will be
“It is a two digit number”. For comparison, ‘-lt’ is used here. For comparison, you can also
use ‘-eq’ for equality, ‘-ne’ for not equality and ‘-gt’ for greater than in bash script.
5
#! /bin/bash
n=10
if [ $n -lt 10 ];
then
echo "It is a one digit number"
else
echo "It is a two digit number"
fi
$ bash simple_if.sh
Different types of logical conditions can be used in if statement with two or more conditions.
How you can define multiple conditions in if statement using AND logic is shown in the
following example. ‘&&’ is used to apply AND logic of if statement. Create a file named
‘if_with_AND.sh’ to check the following code. Here, the value of username and password
variables will be taken from the user and compared with ‘admin’ and ‘secret’. If both values
match then the output will be “valid user”, otherwise the output will be “invalid user”.
#! /bin/bash
6
Run the file with bash command.
$ bash if_with_AND.sh
‘||’ is used to define OR logic in if condition. Create a file named ‘if_with_OR.sh’ with the
following code to check the use of OR logic of if statement. Here, the value of n will be taken
from the user. If the value is equal to 15 or 45 then the output will be “You won the game”,
otherwise the output will be “You lost the game”.
#! /bin/bash
if [[ ( $n -eq 15 || $n -eq 45 ) ]]
then
echo "You won the game"
else
echo "You lost the game"
fi
$ bash if_with_OR.sh
7
Using else if statement:
The use of else if condition is little different in bash than other programming language. ‘elif’ is
used to define else if condition in bash. Create a file named, ‘elseif_example.sh’ and add the
following script to check how else if is defined in bash script.
#! /bin/bash
if [ $n -eq 101 ];
then
echo "You got 1st prize"
elif [ $n -eq 510 ];
then
echo "You got 2nd prize"
elif [ $n -eq 999 ];
then
echo "You got 3rd prize"
else
echo "Sorry, try for the next time"
fi
$ bash elseif_example.sh
Case statement is used as the alternative of if-elseif-else statement. The starting and ending
block of this statement is defined by ‘case’ and ‘esac’. Create a new file named,
‘case_example.sh’ and add the following script. The output of the following script will be same
to the previous else if example.
8
#! /bin/bash
$ bash case_example.sh
Bash script can read input from command line argument like other programming language. For
example, $1 and $2 variable are used to read first and second command line arguments. Create
a file named “command_line.sh” and add the following script. Two argument values read by
the following script and prints the total number of arguments and the argument values as output.
#!/bin/bash
echo "Total arguments : $#"
echo "1st Argument = $1"
echo "2nd argument = $2"
9
You can check the following link to know more about the use of bash command line
argument.
How you can read command line arguments with names is shown in the following script. Create
a file named, ‘command_line_names.sh’ and add the following code. Here, two arguments, X
and Y are read by this script and print the sum of X and Y.
#! /bin/bash
for arg in "$@"
do
index=$(echo $arg | cut -f1 -d=)
val=$(echo $arg | cut -f2 -d=)
case $index in
X) x=$val;;
Y) y=$val;;
*)
esac
done
((result=x+y))
echo "X+Y=$result"
Run the file with bash command and with two command line arguments.
You can easily combine string variables in bash. Create a file named “string_combine.sh” and
add the following script to check how you can combine string variables in bash by placing
variables together or using ‘+’ operator.
#! /bin/bash
string1="Linux"
string2="Hint"
echo "$string1$string2"
string3=$string1+$string2
string3+=" is a good tutorial blog site"
echo $string3
$ bash string_combine.sh
10
Get substring of String:
Like other programming language, bash has no built-in function to cut value from any string
data. But you can do the task of substring in another way in bash that is shown in the following
script. To test the script, create a file named ‘substring_example.sh’ with the following code.
Here, the value, 6 indicates the starting point from where the substring will start and 5 indicates
the length of the substring.
#! /bin/bash
Str="Learn Linux from LinuxHint"
subStr=${Str:6:5}
echo $subStr
$ bash substring_example.sh
You can do the arithmetical operations in bash in different ways. How you can add two integer
numbers in bash using double brackets is shown in the following script. Create a file named
‘add_numbers.sh’ with the following code. Two integer values will be taken from the user and
printed the result of addition.
#! /bin/bash
echo "Enter first number"
read x
echo "Enter second number"
read y
(( sum=x+y ))
echo "The result of addition=$sum"
$ bash add_numbers.sh
You can check the following link to know more about bash arithmetic.
11
Create Function:
How you can create a simple function and call the function is shown in the following script.
Create a file named ‘function_example.sh’ and add the following code. You can call any
function by name only without using any bracket in bash script.
#! /bin/bash
function F1()
{
echo 'I like bash programming'
}
F1
$ bash function_example.sh
Bash can’t declare function parameter or arguments at the time of function declaration. But you
can use parameters in function by using other variable. If two values are passed at the time of
function calling then $1 and $2 variable are used for reading the values. Create a file named
‘function|_parameter.sh’ and add the following code. Here, the function, ‘Rectangle_Area’
will calculate the area of a rectangle based on the parameter values.
#! /bin/bash
Rectangle_Area() {
area=$(($1 * $2))
echo "Area is : $area"
}
Rectangle_Area 10 20
$ bash function_parameter.sh
12
Pass Return Value from Function:
Bash function can pass both numeric and string values. How you can pass a string value from
the function is shown in the following example. Create a file named, ‘function_return.sh’ and
add the following code. The function, greeting() returns a string value into the variable, val
which prints later by combining with other string.
#! /bin/bash
function greeting() {
str="Hello, $name"
echo $str
val=$(greeting)
echo "Return value of the function is $val"
$ bash function_return.sh
You can check the following link to know more about the use of bash functions.
Make Directory:
Bash uses ‘mkdir’ command to create a new directory. Create a file named
‘make_directory.sh’ and add the following code to take a new directory name from the user.
If the directory name is not exist in the current location then it will create the directory,
otherwise the program will display error.
#! /bin/bash
echo "Enter directory name"
read newdir
`mkdir $newdir`
$ bash make_directory.sh
13
Make directory by checking existence:
If you want to check the existence of directory in the current location before executing the
‘mkdir’ command then you can use the following code. ‘-d’ option is used to test a particular
directory is exist or not. Create a file named, ‘directory_exist.sh’ and add the following code
to create a directory by checking existence.
#! /bin/bash
echo "Enter directory name"
read ndir
if [ -d "$ndir" ]
then
echo "Directory exist"
else
`mkdir $ndir`
echo "Directory created"
fi
$ bash directory_exist.sh
You can check the following link to know more about bash directory creation.
Read a File:
You can read any file line by line in bash by using loop. Create a file named, ‘read_file.sh’ and
add the following code to read an existing file named, ‘book.txt’.
#! /bin/bash
file='book.txt'
while read line; do
echo $line
done < $file
14
$ bash read_file.sh
Run the following command to check the original content of ‘book.txt’ file.
$ cat book.txt
You can check the following link to know the different ways to read file in bash.
Delete a File:
‘rm’ command is used in bash to remove any file. Create a file named ‘delete_file.sh’ with the
following code to take the filename from the user and remove. Here, ‘-i’ option is used to get
permission from the user before removing the file.
#! /bin/bash
echo "Enter filename to remove"
read fn
rm -i $fn
$ ls
$ bash delete_file.sh
$ ls
Append to File:
New data can be added into any existing file by using ‘>>’ operator in bash. Create a file named
‘append_file.sh’ and add the following code to add new content at the end of the file. Here,
‘Learning Laravel 5’ will be added at the of ‘book.txt’ file after executing the script.
15
#! /bin/bash
$ bash append_file.sh
You can check the existence of file in bash by using ‘-e’ or ‘-f’ option. ‘-f’ option is used in the
following script to test the file existence. Create a file named, ‘file_exist.sh’ and add the
following code. Here, the filename will pass from the command line.
#! /bin/bash
filename=$1
if [ -f "$filename" ]; then
echo "File exists"
else
echo "File does not exist"
fi
Run the following commands to check the existence of the file. Here, book.txt file exists and
book2.txt is not exist in the current location.
$ ls
$ bash file_exist.sh book.txt
$ bash file_exist.sh book2.txt
16
end Email:
You can send email by using ‘mail’ or ‘sendmail’ command. Before using these commands,
you have to install all necessary packages. Create a file named, ‘mail_example.sh’ and add the
following code to send the email.
#! /bin/bash
Recipient=”admin@example.com”
Subject=”Greeting”
Message=”Welcome to our site”
`mail -s $Subject $Recipient <<< $Message`
$ bash mail_example.sh
You can get the current system date and time value using `date` command. Every part of date
and time value can be parsed using ‘Y’, ‘m’, ‘d’, ‘H’, ‘M’ and ‘S’. Create a new file named
‘date_parse.sh’ and add the following code to separate day, month, year, hour, minute and
second values.
#! /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"
echo "Current Time is: $Hour:$Minute:$Second"
$ bash date_parse.sh
17
Wait Command:
wait is a built-in command of Linux that waits for completing any running
process. wait command is used with a particular process id or job id. If no process id or job id
is given with wait command then it will wait for all current child processes to complete and
returns exit status. Create a file named ‘wait_example.sh’ and add the following script.
#! /bin/bash
echo "Wait command" &
process_id=$!
wait $process_id
echo "Exited with status $?"
$ bash wait_example.sh
You can check the following link to know more about bash linux wait command.
Sleep Command:
When you want to pause the execution of any command for specific period of time then you
can use sleep command. You can set the delay amount by seconds (s), minutes (m), hours (h)
and days (d). Create a file named ‘sleep_example.sh’ and add the following script. This script
will wait for 5 seconds after running.
#! /bin/bash
$ bash sleep_example.sh
18
You can check the following link to know more about bash linux sleep command.
Hope, after reading this article you have got a basic concept on bash scripting language and
you will be able to apply them based on your requirements.
19