Shell Scripting Programs in Linux with Examples
5. Create and Execute BASH SHELL Program:
- The shell is a command line interpreter in Linux.
- Which provides an interface between the user and the operating system.
- The kernel then accesses the hardware and sends the result of the command back to the shell. Shell makes this result of this command show to the user.
- You can execute the command $ echo “$SHELL” to see the current shell.
You can run bash script from the terminal or by executing any bash file. Run the following command from the terminal to execute a very simple bash statement. The output of the command will be ‘Hello World‘.
$ echo “Hello World”
$ nano hello.sh
echo “Hello World”
$ bash hello.sh
$ chmod a+x hello.sh
Use of echo command:
You can use echo command with some following example. Note: ‘-e’ used and interpretation of backslash escape sequence and ‘\n’ tab used for adding a new line and it will printed next to the previous line .Create a new bash file with a name, ‘print.sh’ and add the following script.
echo “Printing text with newline”
echo -e “Gyancs is\n A Completer Learning Education”
$ bash print.sh
Use of comment:
‘#’ symbol is used to add single line comment in bash script. Create a new file named ‘cnt.sh‘ and add the following script with single line comment.
# Add two numeric value
#Print the result
$ bash cnt.sh
Use of Multi-line comment:
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, ‘mlc.sh‘ and add the following script. Here, ’:’ and ” ’ ” symbols are used to add multiline comment in bash script.
The following script calculates
the square value of the number, 5.
$ bash mlc.sh
Using For Loop:
The basic for loop declaration is shown in the following example. Create a file named ‘for_exp.sh‘ . Here, for loop will iterate for 10 times and print all values of the variable, counter in single line.
for (( counter=1; counter<=10; counter++ ))
echo -n “$counter “
$ bash for_exp.sh
Using While Loop:
Create a bash file with the name, ’while_exp.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.
while [ $i -le 2 ]
echo Number: $i
$ bash while_exp.sh
‘read’ command is used to take input from user . Create a file named ‘read.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.
echo “Enter Your Name”
echo “Welcome $name to Gyancs”
$ bash u_input.sh
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 ‘if_s.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.
if [ $n -lt 10 ];
echo “It is a one digit number”
echo “It is a two digit number”
$ bash if_s.sh
Using if statement with AND logic:
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_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”.
echo -n “Enter Number:”
if [[ ( $num -lt 10 ) && ( $num%2 -eq 0 ) ]]; then
echo “Even Number”
echo “Odd Number”
$ bash if_and.sh
Using if statement with OR logic:
‘||’ is used to define OR logic in if condition. Create a file named ’if_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”.
echo -n “Enter any number:”
if [[ ( $n -eq 15 || $n -eq 45 ) ]]
echo “You won”
echo “You lost!”
$ bash if_or.sh
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_exp.sh’ and add the following script to check how else if is defined in bash script.
echo “Enter your lucky number”
if [ $n -eq 101 ];
echo “You got 1st prize”
elif [ $n -eq 510 ];
echo “You got 2nd prize”
elif [ $n -eq 999 ];
echo “You got 3rd prize”
echo “Sorry, try for the next time”
$ bash elseif_exp.sh
Using Case Statement:
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_exp.sh’ and add the following script. The output of the following script will be same to the previous else if example.
echo “Enter Your Choice Number”
case $r in
echo “You have 1st Choice” ;;
echo “You have 2nd Choice” ;;
echo “You have 3rd Choice” ;;
echo “Wrong Choice, Try Next Time” ;;
$ bash case_exp.sh
6. How to get arguments from Command Line:
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 ‘cmd_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.
echo “Total arguments : $#”
echo “1st Argument = $1”
echo “2nd argument = $2”
$ bash cmd_line.sh Unix Linux
Total arguments :2
1st Argument = Unix
2nd argument = Linux
Combine String :
You can easily combine string variables in bash. Create a file named ‘str_combine.sh’ and add the following script to check how you can combine string variables in bash by placing variables together or using ’+’ operator.
string3+=” is a good Educational website”
$ bash str_combine.sh
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 ‘substr_exp.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.
Str=”Learn Linux from Gyancs”
$ bash substr_exp.sh
Add Two Numbers:
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_num.sh’ with the following code. Two integer values will be taken from the user and printed the result of addition.
echo “Enter first number”
echo “Enter second number”
(( sum=x+y ))
echo “The result of addition=$sum”
$ bash add_num.sh
How you can create a simple function and call the function is shown in the following script. Create a file named ‘func_exp.sh’ and add the following code. You can call any function by name only without using any bracket in bash script.
echo ‘I like bash programming’
$ bash func_expe.sh
Function with Parameters:
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 ‘func|_para.sh’ and add the following code. Here, the function, ‘Rectangle Area’ will calculate the area of a rectangle based on the parameter values.
area=$(($1 * $2))
echo “Area is : $area”
Rectangle_Area 10 20
$ bash func_para.sh
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, ‘func_ret.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.
echo “Enter your name”
echo “Return value of the function is $val”
$ bash func_ret.sh
Bash uses ‘mkdir’ command to create a new directory. Create a file named ‘mk_dir.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.
echo “Enter directory name”
$ bash mk_dir.sh
Create 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, ‘dir_exist.sh’ and add the following code to create a directory by checking existence.
echo “Enter directory name”
if [ -d “$ndir” ]
echo “Directory exist”
echo “Directory created”
$ bash dir_exist.sh
Read a File:
You can read any file line by line in bash by using loop. Create a file named, ‘rd_file.sh’ and add the following code to read an existing file named, ‘book.txt’.
while read line; do
done < $file
$ bash rd_file.sh
1. Pro AngularJS
2. Learn JQuery
3. PHP Programming
4. Code Integer 3
$ cat book.txt
1. Pro AngularJS
2. Learn JQuery
3. PHP Programming
4. Code Integer 3
Remove a File:
‘rm’ command is used in bash to remove any file. Create a file named ‘del_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.
echo “Enter filename to remove”
rm -i $fn
$ bash del_file.sh
Enter filename to remove
rm: remove regular file ‘book.txt’? y
New data can be added into any existing file by using ’>>‘ operator in bash. Create a file named ’app_file.sh’ and add the following code to add new content at the end of the file. Here, ‘Learning Lavel 5’ will be added at the of ‘book.txt’ file after executing the script.
echo “Before appending the file”
echo “Learning Lavel 5”>> book.txt
echo “After appending the file”
$ bash app_file.sh
Test if File Exist:
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, ‘f_exist.sh’ and add the following code. Here, the filename will pass from the command line.
if [ -f “$filename” ]; then
echo “File exists”
echo “File does not exist”
$ bash f_exist.sh book.txt
$ bash f_exist.sh book2.txt
Parse Current Date:
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 ‘d_parse.sh‘ and add the following code to separate day, month, year, hour, minute and second values.
echo “Current Date is: $Day-$Month-$Year”
echo “Current Time is: $Hour:$Minute:$Second”
$ bash d_parse.sh
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_exp.sh’ and add the following script.
echo “Wait command” &
echo “Exited with status $?”
$ bash wait_exp.sh
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_exp.sh‘ and add the following script. This script will wait for 5 seconds after running.
echo “Wait for 5 seconds”
$ bash sleep_exp.sh