Shell Scripting Programs in Linux with Examples

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

#!/bin/bash
echo “Hello World”

$ bash hello.sh

Or

$ chmod a+x hello.sh
$ ./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.

#!/bin/bash
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.

#!/bin/bash
# Add two numeric value
((sum=25+35))
#Print the result
echo $sum

$ 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.

#!/bin/bash
: ‘
The following script calculates
the square value of the number, 5.

((area=5*5))
echo $area

$ 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.

#!/bin/bash
for (( counter=1; counter<=10; counter++ ))
do
echo -n “$counter “
done
printf “\n”

$ 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.

#!/bin/bash
i=0

while [ $i -le 2 ]
do
echo Number: $i
((i++))
done

$ bash while_exp.sh

User Input:
‘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.

#!/bin/bash
echo “Enter Your Name”
read 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.

#!/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 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”.

#!/bin/bash
echo -n “Enter Number:”
read num
if [[ ( $num -lt 10 ) && ( $num%2 -eq 0 ) ]]; then
echo “Even Number”
else
echo “Odd Number”
fi

$ 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”.

#!/bin/bash
echo -n “Enter any number:”
read n
if [[ ( $n -eq 15 || $n -eq 45 ) ]]
then
echo “You won”
else
echo “You lost!”
fi

$ 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.

#!/bin/bash
echo “Enter your lucky number”
read n
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_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.

#!/bin/bash
echo “Enter Your Choice Number”
read r
case $r in
1)
echo “You have 1st Choice” ;;
2)
echo “You have 2nd Choice” ;;
3)
echo “You have 3rd Choice” ;;
0)
echo “Wrong Choice, Try  Next Time” ;;
esac

$ 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.

#!/bin/bash
echo “Total arguments : $#”
echo “1st Argument = $1”
echo “2nd argument = $2”

$ bash cmd_line.sh Unix Linux
Output:
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.

#!/bin/bash
string1=”Gyan”
string2=”cs”
echo “$string1$string2”
string3=$string1+$string2
string3+=” is a good Educational website”
echo $string3

$ 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.

#!/bin/bash
Str=”Learn Linux from Gyancs”
subStr=${Str:6:5}
echo $subStr

$ 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.

#!/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_num.sh

Function:
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.

#!/bin/bash
function F1()
{
echo ‘I like bash programming’
}
F1

$ 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.

#!/bin/bash
Rectangle_Area()
{
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.

#!/bin/bash
function greeting()
{
str=”Hello, $name”
echo $str
}
echo “Enter your name”
read name
val=$(greeting)
echo “Return value of the function is $val”

$ bash func_ret.sh

Create Directory:
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.

#!/bin/bash
echo “Enter directory name”
read newdir
`mkdir $newdir`

$ 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.

#!/bin/bash
echo “Enter directory name”
read ndir
if [ -d “$ndir” ]
then
echo “Directory exist”
else
`mkdir $ndir`
echo “Directory created”
fi

$ 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’.

#!/bin/bash
file=’book.txt’
while read line; do
echo $line
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.

#!/bin/bash
echo “Enter filename to remove”
read fn
rm -i $fn

$ ls
$ bash del_file.sh
Enter filename to remove
book.txt
rm: remove regular file ‘book.txt’? y

$ ls

Append  File:
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.

#!/bin/bash
echo “Before appending the file”
cat book.txt
echo “Learning Lavel 5”>> book.txt
echo “After appending the file”
cat book.txt

$ 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.

#!/bin/bash
filename=$1
if [ -f “$filename” ]; then
echo “File exists”
else
echo “File does not exist”
fi

$ ls
$ 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.

#!/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 d_parse.sh

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_exp.sh and add the following script.

#!/bin/bash
echo “Wait command” &
process_id=$!
wait $process_id
echo “Exited with status $?”

$ bash wait_exp.sh

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_exp.sh and add the following script. This script will wait for 5 seconds after running.

#!/bin/bash
echo “Wait for 5 seconds”
sleep 5
echo “Completed”

$ bash sleep_exp.sh



Open Source Software Lab Manual


About me