4CS4-24 Linux Shell Programming Lab
4CS4-24 Linux Shell Programming Lab
Semester: IV
Session 2019-20
Faculty:
Ashish Pant
(Assistant Professor)
If you are using any major operating system you are indirectly interacting to shell. If you are
running Ubuntu, Linux Mint or any other Linux distribution, you are interacting to shell every
time you use terminal.
What is Shell
A shell is special user program which provide an interface to user to use operating system
services. Shell accept human readable commands from user and convert them into something
which kernel can understand. It is a command language interpreter that execute commands
read from input devices such as keyboards or from files. The shell gets started when the user
logs in or start the terminal.
Shell can be accessed by user using a command line interface. A special program
called Terminal in linux/macOS or Command Prompt in Windows OS is provided to type in the
human readable commands such as “cat”, “ls” etc. and then it is being execute.
There are several shells are available for Linux systems like –
BASH (Bourne Again SHell) – It is most widely used shell in Linux systems. It is used as
default login shell in Linux systems and in macOS. It can also be installed on Windows OS.
Bash is a command language interpreter. It is widely available on various operating
systems and is a default command interpreter on most GNU/Linux systems. The name is
an acronym for the ‘Bourne-Again SHell’.
CSH (C SHell) – The C shell’s syntax and usage are very similar to the C programming
language.
KSH (Korn SHell) – The Korn Shell also was the base for the POSIX Shell standard
specifications etc.
Each shell does the same job but understand different commands and provide different built in
functions. We will now onwards focus on Bash Shell only.
Shell Scripting
Usually shells are interactive that mean, they accept command as input from users and execute
them. However some time we want to execute a bunch of commands routinely, so we have
type in all commands each time in terminal.
As shell can also take commands as input from file we can write these commands in a file and
can execute them in shell to avoid this repetitive work. These files are called Shell
Scripts or Shell Programs. Shell scripts are similar to the batch file in MS-DOS. Each shell script
is saved with .sh file extension eg. myscript.sh
A shell script have syntax just like any other programming language. If you have any prior
experience with any programming language like Python, C/C++ etc. it would be very easy to get
started with it.
A shell script comprises following elements –
Shell Keywords – if, else, break etc.
Shell commands – cd, ls, echo, pwd, touch etc.
Functions
Control flow – if..then..else, case and shell loops etc.
A shell script is not compiled but interpreted by bash shell (command line intrerpetor)
echo
echo command inserts a new line automatically.
If we don’t wish to get new line then use -n
echo -n “Enter any number : ”
Write first script program (Hello World Bash Shell Script)
Execute
Note :
The sign #! is called she-bang and is written at top of the script. It passes instruction to
program /bin/bash. To run your script in a certain shell (shell should be supported by your
system), start your script with #! followed by the shell name. It tells to use bash as command
interpreter. It is not mandatory to use she-bang. # is used for single line comment.
: ‘ ……………… ‘ for multi line comments. To insert a new line simply write echo
Output
Variables
Variable declaration is a necessary part of any programming language. Bash variables can be
declared in different ways. When a value is assigned in a variable then no symbol is used at the
beginning of the variable. ‘$’ symbol is used with the variable name at the time of reading the
value of the variable.
Output
Script to read from keyboard
Output
Command substitution and shell variables
You can store command output to a shell variable using the following syntax:
var=$(command-name)
or
var=`command-name` where ` is backtick symbol
NOW=$(date)
echo "$NOW"
Experiment No. 3
Shell Programming: Shell script based on control structure- If-then-fi, if-then else-
if, nested if-else
Bash If
In this topic, we will understand how to use if statements in Bash scripts to get our automated
tasks completed.
Bash if statements are beneficial. They are used to perform conditional tasks in the sequential
flow of execution of statements. If statements usually allow us to make decisions in our Bash
scripts. They help us to decide whether or not to run a piece of codes based upon the condition
that we may set.
Basic if Statements
A basic if statement commands that if a particular condition is true, then only execute a given
set of actions. If it is not true, then do not execute those actions. If statement is based on the
following format:
Syntax
if [ expression ]; then #space after [ and before ]
statements
fi
or
if [ expression ]
then
statements
fi
if [ expression ]
then
statements
else
statements
fi
The statement between then and fi (If backwards) will be executed only if the expression
(between the square brackets) is true.
Note: Observe the spaces used in the first line (inside square bracket) and a semicolon at the
end of the first line; both are mandatory to use. If conditional statement ends with fi.
We ahould use [[ ]] (double square brackets) if we are using logical operators (&& or || )
inside if (using more than one condition.)
String Comparison
When creating a bash script, we might also be required to compare two or more strings &
comparing strings can be a little tricky. For doing strings comparisons, parameters used are
Note :- You might have noticed that greater than symbol (>) & less than symbol (<) used here
are also used for redirection for stdin or stdout in Linux. This can be a problem when these
symbols are used in our scripts, so what can be done to address this issue.
Solution is simple , when using any of these symbols in scripts, they should be used with escape
character i.e. use it as “\>” or “\<“.
1. if [ ] && [ ]
or
if [[ && ]]
if [ ]
then
if [ ]
then
fi
fi
3. Double-parenthesis syntax
There also is another syntax for arithmetic (number-based) conditions,
or
if (($num <=5))
then
or
if((a==b)); then
The above condition is true if $num is less than or equal to 5. This syntax may seem more
familiar to programmers. It features all the ‘normal’ operators, like “==”, “<” and “>=”. It
supports the “&&” and “||” combining expressions
Output
Experiment No. 3.1
Write a Shell script to find the greatest among three numbers.
Output
Enter Num1
1
Enter Num2
34
Enter Num3
2
34 is greatest
Experiment No. 3.2
Write a Shell script to find a year is leap year or not.
Output
Experiment No. 3.3
Write a Shell script to input angles of a triangle and find out whether it is valid
triangle or not.
Output
Experiment No. 3.4
Write a Shell script to check whether a character is alphabet, digit or special
character.
Regular expression is a pattern for a matching string that follows some pattern.
We here use regular expression for matching. =~ is regular expression match operator used for
matching regular expression.
This pattern will match a single character that is a letter, number, or underscore:
[A-Za-z0-9_]
d.g
This regex means we are looking for a word that starts with ‘d’, ends with ‘g’ & can have any
character in the middle in the file named ‘file_name’. Similarly, we can use dot character any
number of times for our search pattern, like
T……h
This search term will look for a word that starts with ‘T’, ends with ‘h’ & can have any six
characters in the middle.
N[oen]
here, we are looking for a word that starts with ‘N’, ends with ‘n’ & can only have either of ‘o’
or ‘e’ or ‘n’ in the middle. We can mention from a single to any number of characters inside
the square braces.
We can also define ranges like ‘a-e’ or ‘1-18’ as the list of matching characters inside square
braces.
[^ ]
This is like the not operator for regex. While using [^ ], it means that our search will include all
the characters except the ones mentioned inside the square braces. Example,
“St[^1-9]d” file3
This means that we can have all the words that start with ‘St’, ends with letter ‘d’ & must not
contain any number from 1 to 9.
Output
Experiment No. 3.5
Write a shell script to calculate profit or loss.
Output
Experiment No. 4
do
done
Where, variable holds an item from the list of multiple items. There are some key points of 'for
loop' statement:
o Each block of 'for loop' in bash starts with 'do' keyword followed by the commands
inside the block. The 'for loop' statement is closed by 'done' keyword.
o The number of time for which a 'for loop' will iterate depends on the declared list
variables.
o The loop will select one item from the list and assign the value on a variable which will
be used within the loop.
o After the execution of commands between 'do' and 'done', the loop goes back to the
top and select the next item from the list and repeat the whole process.
o The list can contain numbers or string etc. separated by spaces.
o By default increment decrement is by one.
Example:
for i in {1..5}
do
echo "Ashish"
done
The above script also prints the name 5 times.
do
echo “$i”
done
for i in {10..1..2}
do
echo "$i"
done
for i in {A..Z..2}
do
echo "$i"
done
Note : We can not use any variable like for i in {1..$var}. Instead try to use C style for loop
discussed later.
seq command
We use the seq command to generate numeric sequence.
Example:
seq LAST
10
seq FIRST INCREMENT LAST
#!/bin/sh
do
echo $i
done
str="Let's start
learning
shell programming.”
for i in "$str"
do
echo "$i"
done
do
done
initialization
while [ condition ] #space after [ and before ]
do
commands
multiple commands
increment/decrement
done
Example
1. #!/bin/bash
2. #Script to get specified numbers
3.
4. read -p "Enter starting number: " snum
5. read -p "Enter ending number: " enum
6.
7. while [ $snum -le $enum ]
8. do
9. echo $snum
10. ((snum++))
11. done
12.
13. echo "This is the sequence that you wanted."
Output
#An infinite while loop
while :
do
echo "Welcome."
done
or
1.
while :; do echo "Welcome to Javatpoint."; done
or
1. while true
2. do
3. echo "Welcome to Javatpoint"
4. done
1. i=1
2. while((i <= 10))
3. do
4. echo $i
5. ((i++)) # or we can write let i++
6. done
until loop
The set of commands are executed only until the condition becomes true It means that when
the expression evaluates to false, a set of commands are executed iteratively. The loop is
terminated as soon as the expression evaluates to true for the first time.
In short, the until loop is similar to the while loop but with a reverse concept.
#!/bin/bash
counter=0
The loop iterates as long as the counter variable has a value greater than four. The script will
produce the following output:
Counter: 0
Counter: 1
Counter: 2
Counter: 3
Counter: 4
Counter: 5
Experiment No. 4.1
Write a shell script to print all even and odd number from 1 to 10.
Output
Experiment No. 4.2
Write a shell script to print multiplication table of a given number.
Output
Experiment No. 4.3
Write a shell script to calculate factorial of a given number.
Output
Experiment No. 4.4
Write a shell script to print sum of all even numbers from 1 to 10.
Output
Experiment No. 4.5
Write a shell script to print sum of digit of any number.
Output
Experiment No. 5
case expression in
pattern-1)
statements
;;
pattern-2)
statements
;;
pattern-3|pattern-4|pattern-5)
statements
;;
pattern-N)
statements
;;
*) #default case
statements
;;
esac
o Each case statement in bash starts with the 'case' keyword, followed by the case
expression and 'in' keyword. The case statement is closed by 'esac' keyword.
o We can apply multiple patterns separated by | operator. The ) operator indicates the
termination of a pattern list.
o A pattern containing the statements is referred to as a clause, and it must be terminated
by double semicolon (;;). This is similar to break in the C programming language.
o An asterisk symbol (*) is used as a final pattern to define the default case. It is used as a
default case when used as the last case.
o A pattern can have special characters.
Case Statement Example
Here is an example using the case statement in a bash script that will print the official language
of a given country:
languages.sh
case $COUNTRY in
India)
echo "Hindi & English"
;;
Romania | Moldova)
echo "Romanian"
;;
*)
echo "unknown"
;;
esac
Output
Break Statement
We can use break and continue in loops with if ,same as we did in C programs.
Experiment No. 5.1
Write a shell script to make a basic calculator which performs addition,
subtraction, multiplication, division.
Output
Experiment No. 5.2
Write a shell script to print days of a week.
Output
Experiment No. 5.3
Write a shell script to print starting 4 months having 31 days.
c=0
for m in {1..12}
do
case $m in
1)
month=January
days=31
;;
2)
month=February
days=29 #considering 2020
;;
3)
month=March
days=31
;;
4)
month=April
days=30
;;
5)
month=May
days=31
;;
6)
month=June
days=30
;;
7)
month=July
days=31
;;
8)
month=August
days=31
;;
9)
month=September
days=31
;;
10)
month=October
days=31
;;
11)
month=November
days=30
;;
12)
month=December
days=31
;;
esac
if [ $days -ne 31 ]; then
continue
else
echo "$month - $days days"
((c++))
if [ $c -eq 4 ]; then
break
fi
fi
done
Output
Experiment No. 6
A Bash function is essentially a set of commands that can be called numerous times. The
purpose of a function is to help you make your bash scripts more readable and to avoid writing
the same code over and over again.
Compared to most programming languages, Bash functions are somewhat limited. In this
tutorial, we will cover the basics of Bash functions and show you how to use them in your shell
scripts.
The syntax for declaring a bash function is very simple. They may be declared in two different
formats:
1. The first format starts with the function name, followed by parentheses. This is the
preferred and more used format.
2. function_name () {
3. commands
}
Or
function_name ()
{
Commands
}
function_name () { commands; }
4. The second format starts with the function reserved word followed by the function
name.
5. function function_name {
6. commands
}
Single line version:
The command list between curly braces {} is the body of the function. The curly braces
that surround the function body must be separated from the body by spaces or
newlines.
Defining a function doesn’t execute it. To invoke a bash function, simply use the
function name. Commands between the curly braces are executed whenever the
function is called in the shell script.
The function definition must be placed before any calls to the function.
When using single line “compacted” functions, a semicolon ; must follow the last
command in the function.
You should always try to keep your function names descriptive.
Function should always be defined before calling
~/hello_world.sh
#!/bin/bash
hello_world () {
echo “hello, world script”
}
hello_world
On line 3 we are defining the function by giving it a name, and opening the curly
brace { that marks the start of the function’s body.
Line 4 is the function body. The function body can contain multiple commands and
variable declarations.
Line 5, the closing curly bracket }, defines the end of the hello_world function.
On line 7 we are executing the function. You can execute the function as many times as
you need.
Variables Scope
Global variables are variables that can be accessed from anywhere in the script regardless of
the scope. In Bash, all variables by default are defined as global, even if declared inside the
function.
Local variables can be declared within the function body with the local keyword and can be
used only inside that function. You can have local variables with the same name in different
functions.
To better illustrate how variables scope works in Bash, let’s consider an example:
~/variables_scope.sh
#!/bin/bash
var1='A'
var2='B'
my_function () {
local var1='C'
var2='D'
echo "Inside function: var1: $var1, var2: $var2"
}
my_function
The script starts by defining two global variables var1 and var2. Then a function that sets a local
variable var1 and modifies the global variable var2.
If you run the script, you should see the following output:
If you set a local variable inside the function body with the same name as an existing
global variable, it will have precedence over the global variable.
Global variables can be changed from within the function
Passing Arguements to a Function
You can define a function that will accept parameters while calling the function. These
parameters would be represented by $1, $2 and so on.
Following is an example where we pass two parameters Zara and Ali and then we capture and
print these parameters in the function.
Live Demo
#!/bin/sh
Hello Zara Ali #function calling Zara & Ali are arguments
Upon execution, you will receive the following result −
$./test.sh
Hello World Zara Ali
Note : bash function name must be unique. Otherwise, the new function will cancel the old
function without any errors
To pass any number of arguments to the bash function simply put them right after the
function’s name, separated by a space. It is a good practice to double-quote the arguments to
avoid misparsing of an argument with spaces in it.
The passed parameters are $1, $2, $3 … $n, corresponding to the position of the
parameter after the function’s name.
The $0 variable is reserved for the function’s name.
The $# variable holds the number of positional parameters/arguments passed to the
function.
The $* and $@ variables holds all positional parameters/arguments passed to the
function.
When double quoted, "$*" expands to a single string separated by space (the
first character of IFS) - "$1 $2 $n".
When double quoted, "$@" expands to separate strings - "$1" "$2" "$n".
When not double quoted, $* and $@ are the same.
Here is an example:
~/passing_arguments.sh
#!/bin/bash
greeting () {
echo "Hello $1"
}
greeting Ashish
greeting “Ashish Pant”
output
Hello Ashish
Hello Ashish Pant
#!/bin/bash
greeting () {
echo "Hello $1 $2"
}
output
greeting ()
{
echo "Hello $1"
echo "$2 How are you doing?"
}
Output
Hello Ashish
Pant How are you doing?
Returning Values from Functions
Aside from creating functions and passing parameters to it, bash functions can pass the values
of a function's local variable to the main routine by using the keyword return. The returned
values are then stored to the default variable $? For instance, consider the following code:
add(){
sum=$(($1+$2))
return $sum
}
Output
Enter an integer: 4
Enter an integer: 9
The result is: 13
To actually return an arbitrary value from a function, we need to use other methods. The
simplest option is to assign the result of the function to a global variable:
~/return_values.sh
#!/bin/bash
my_function () {
func_result="some result"
}
my_function
echo $func_result
This method can return integer as well as string values.
}
add $int1 $int2
echo "The result is: $sum"
echo "$str"
Output
Enter an integer: 5
Enter an integer: 6
The sum is: 11
addition completed!
Method 3
Another, better option to return a value from a function is to send the value
to stdout using echo or printf like shown below.
We can receive the return value of a bash function and store it in a variable at the time of
calling.
Instead of simply executing the function which will print the message to stdout, we are
assigning the function output to the result variable using the $() command substitution. The
variable can later be used as needed.
Example
In the following example, the return value of the function is set based on the argument variable
of the function. Here, a value is passed to the function F3 by using an argument variable,
getval1 at the time of function calling. After checking conditional statement, the return value is
assigned and printed.
function F3()
{
local arg1=$1
getval1="Bash Function"
F3 $getval1
echo $retval
getval2=$(F3)
echo $getval2
Output
Experiment No. 6.1
Write a shell script to find a number is Armstrong or not.
Armstrong number is an n-digit number that is equal to the sum of the nth powers of its digits.
Output
Experiment No. 6.2
Write a shell script to find a number is palindrome or not.
Output
Experiment No. 6.3
Write a shell script to print Fibonacci series.
Output
Experiment No. 6.4
Write a shell script to find number is prime number or not.
Output
Experiment No. 6.5
Write a shell script to convert binary to decimal and decimal to binary.
Output
Experiment No. 7
Write a shell script to print different shapes- Diamond, triangle,
square, rectangle, hollow square etc.
Output
Experiment No. 7.2
Output
Experiment No. 7.3
Output
Experiment No. 7.4
Output
Experiment No. 7.5
Output