SWAMI KESHVANAND INSTITUTE OF TECHNOLOGY,
MANAGEMENT AND GRAMOTHAN, JAIPUR
Hands-On Lab Guide
Linux Shell Programming Lab (4CS4-24)
Semester: IV
Branch: Computer Science & Engineering
Session 2019-20
Faculty:
Ashish Pant
(Assistant Professor)
Department of Computer Science & Engineering
Swami Keshvanand Institute of Technology, Management & Gramothan,
Ramnagaria, Jaipur-302017
Linux Shell Programming Lab
Rajasthan Technical University
Swami Keshvanand Institute of Technology and Gramothan, Jaipur
B.Tech (Computer Science & Engineering ), IV Semester
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)
bash filename.sh or ./ filename.sh
Why do we need shell scripts
There are many reasons to write shell scripts –
To avoid repetitive work and automation
System admins use shell scripting for routine backups
System monitoring
Adding new functionality to the shell etc.
Use gedit(if using ubuntu virtual machine or installed) or nano editor (if used in windows) for
linux shell scripting. Install nano if using wsl on windows 10 by command sudo apt install nano
To see what is your default interpreter execute command
echo $SHELL
output( path to default shell or interpreter) : /bin/bash
How to write shell script
1. Write the script in any editor (gedit, nano etc) and save it as .sh file.
2. Make it exectable(if needed) by command chmod +x filename.sh or
chmod 755 file.sh
3. Execute the script by : bash filename.sh
Step 2 may be ignored.
Nano Editor
Install by : sudo apt install nano
It is not gui based but command based.
^ means press ctrl key
^s : Save
^G : ctrl+G for help and knowing about commands.
^X : Exit
Right click on mouse : Paste text copied from somewhere.
Write script.
Open nano editor by writing following command in nano
nano filename.sh
Write the required script
Ctrl+x to exit . Press Y to save.
To open and edit a existing script in nano. Write following command in terminal.
nano filename.sh
Then move cursor by arrow keys and edit.
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
A shell script to execute many commands together.
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.
mystr="I like bash programming"
echo $mystr
x=Ashish or x=“Ashish” // no space before or after =
//double quotes if more than one word assigned to
Variable. But for echo double quotes not
Necessary but keep them as a good practice.
X = 5 // wrong as space before and after
X=5 //right
x=2 or x=”2”
var=”Sachin Tendulkar”
Numerical Values are taken as strings.
The shell does not care about types of variables; they may store strings, integers, real numbers
- anything you like.
var=1.5
var=1
var= a
Read value from keyboard
echo “What is your name”
read a
echo “ $a ! Welcome to shell programming”
echo $a, so how are you?
echo “enter any number”
read a
echo “enter two numbers”
read a
read b
or
read a b
we enter the input on the same PROMPT by using the -p command line option as follows:
read “enter two numbers” a b
Arithmetic Expressions
x=5
y=10
i=4
ans=$((x+y)) //double parentheses for arithmetic expression
echo “$ans”
((m=x+y))
echo “$m”
((i++))
Echo “$i”
Or use let command
let y=25+9
echo $y
let i++
Assign
car=honda
new_car= $car
echo $new_car
Example
Output
Script to read from keyboard
Output
Command substitution and shell variables
echo "Today is $(date)"
You can store command output to a shell variable using the following syntax:
var=$(command-name)
or
var=`command-name` where ` is backtick symbol
Store current date and time to a variable called NOW:
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.)
Always use [[ ]] with if , during pattern matching using regular expression.
If [ ] gives error with if, try to use [[ ]]
Numeric and String Comparisons
Description Numeric Comparison String Comparison
less than -lt < (use \>)
greater than -gt > \>
equal -eq = or == if [[ ]] are used
not equal -ne !=
less or equal -le N/A
greater or equal -ge N/A
Regular expression matching operator =~
string1 =~ regex- The regex operator returns true if the left operand matches the extended
regular expression on the right.
We can invert a condition by !
After reviewing the above table, let's say, we would like to compare numeric values like two
integers 1 and 2 .
Next, we use square brackets and numeric comparison operators to perform the actual
evaluation. Using echo $? command, we check for a return value of the previously executed
evaluation. There or two possible outcomes for every evaluation, true or false. If the return
value is equal to 0 , then the comparison evaluation is true. However, if the return value is
equal to 1 , the evaluation resulted as false.
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
str1 = str2 checks if str1 is the same as str2
str1 != str2 checks if var1 is not the same as var2
str1 \< str2 str1 sorts before str2 lexicographically (use
str1 \> str2 str1 sorts after str2 lexicographically
-n str1 checks if str1 has a length greater than zero (Non empty string)
-z str1 checks if str1 has a length of zero (Empty String)
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 [[ (condition && condition) || (condition && condition) ]]; then
...
fi
2. # Nested if statements
if [ ]
then
if [ ]
then
fi
fi
3. Double-parenthesis syntax
There also is another syntax for arithmetic (number-based) conditions,
if (($num <=5)); then
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
4. Bash Else If – elif If-else-if Ladder (if elif else)
if <expression>; then
<commands>
elif <expression>; then
<commands>
else
<commands>
fi
Use of if else
Output
Experiment No. 3.1
Write a Shell script to find the greatest among three numbers.
#shell script to find the greatest of three numbers
echo "Enter Num1"
read num1
echo "Enter Num2"
read num2
echo "Enter Num3"
read num3
if [ $num1 -gt $num2 ] && [ $num1 -gt $num3 ]
then
echo “$num1 is greatest”
elif [[ $num2 -gt $num1 && $num2 -gt $num3 ]]
then
echo “$num2 is greatest”
else
echo “$num3 is greatest”
fi
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_]
Always use [[ ]] with if while pattern matching using regular expression.
. or Dot will match any character
[] will match a range of characters. Hyphen -for range.
[^ ] will match all character except for the one mentioned in braces
* will match zero or more of the preceding items
+ will match one or more of the preceding items
? will match zero or one of the preceding items
{n} will match ‘n’ numbers of preceding items
{n,} will match ‘n’ number of or more of preceding items
{n m} will match between ‘n’ & ‘m’ number of items
{ ,m} will match less than or equal to m number of items
^ Matches start of string and represents characters not in the string.
^aa pattern starting with aa.
$ Matches end of pattern. $aa means pattern ending with aa
^$ Blank patterns,
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.
Shell Script to check whether a character is alphabet, digit or special character.
Output
Experiment No. 3.5
Write a shell script to calculate profit or loss.
Output
Experiment No. 4
Shell Programming - Looping- while, until, for loops
Bash for Loop
for variable in items
do
# code for each item
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.
Shell Script to print your name 5 times using for loop
for i in 1 2 3 4 5
do
echo "Ashish"
done
Ashish
Ashish
Ashish
Ashish
Ashish
We use the brace expansion {m..n} for a range to generate string in shell script.
Example:
{1..5} will give 1 2 3 4 5
{a..f} will give a b c d e f
{Z..T} will give Z Y X W V U T
{-5..5} will give -5 -4 -3 -2 -1 0 1 2 3 4 5
{A,B,C,D} will give A B C D
{A,B,C{1..3},D} will give A B C1 C2 C3 D
for i in {1..5}
do
echo "Ashish"
done
The above script also prints the name 5 times.
If we want to print numbers from 5 to 10
for i in 5 6 7 8 9 10 # or we can write for i in {5..10}
do
echo “$i”
done
Script to print numbers from 10 to 1 with decrement by 2
for i in {10..1..2}
do
echo "$i"
done
Script to print A C E……Y
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
so, seq 5 will give
seq FIRST LAST
so, seq 7 10 will give
10
seq FIRST INCREMENT LAST
so, seq 1 2 10 will give
Shell Script to print all odd numbers from 1 to 10
#!/bin/sh
for i in $(seq 1 2 10)
do
echo $i
done
#For Loop to Read string
for i in "hello how are you"
do
echo "$i"
done
Output : hello how are you
for i in hello how are you
do
echo "$i"
done
Output
hello
how
are
you
str="Let's start learning shell programming.”
for i in "$str"
do
echo "$i"
done
Output : Let's start learning shell programming
str="Let's start
learning
shell programming.”
for i in "$str"
do
echo "$i"
done
Output : Let's start
learning
shell programming
for loop like C programming
for (( var=val; var<=val2; var++ ))
do
# body of for loop
done
We can use break and continue in loops.
While loop
initialization
while [ condition ] #space after [ and before ]
do
commands
multiple commands
increment/decrement
done
one liner syntax
while [ condition ]; do commands; 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
While Loop with C-Style
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.
1. until [ expression ]; # space after [ and before ]
2. do
3. command1
4. command2
5. ...
6. ....
7. commandN
8. done
#!/bin/bash
counter=0
until [ $counter -gt 5 ] #or we can write as c style until((counter>6))
do
echo “Counter: $counter”
((counter++))
done
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
Shell Programming - case structure, use of break
Basic Syntax of the CASE Statement
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
echo "Enter the name of a country: "
read COUNTRY
echo "The official language of $COUNTRY is "
case $COUNTRY in
India)
echo "Hindi & English"
;;
Romania | Moldova)
echo "Romanian"
;;
Italy | "San Marino" | Switzerland | "Vatican City")
echo "Italian"
;;
*)
echo "unknown"
;;
esac
Output
Enter the name of a country: Lithuania
The official language of Lithuania is Lithuanian
Enter the name of a country: Argentina
The official language of Argentina is unknown
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
Shell Programming – Functions
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.
Bash Function Declaration
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
}
Single line version:
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:
function function_name { commands; }
Few points to be noted:
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
To understand this better, take a look at the following example:
~/hello_world.sh
#!/bin/bash
hello_world () {
echo “hello, world script”
}
hello_world
If you run the script, it will print hello, world script
Let’s analyze the code line by line:
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"
}
echo "Before executing function: var1: $var1, var2: $var2"
my_function
echo "After executing function: var1: $var1, var2: $var2"
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:
Before executing function: var1: A, var2: B
Inside function: var1: C, var2: D
After executing function: var1: A, var2: D
From the output above, we can conclude that:
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
# Define your function here
Hello () {
echo "Hello World $1 $2" #$1 and $2 are parameters
}
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
Passing Arguments to Bash Functions
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"
}
greeting Ashish Rahul
greeting “Ashish Pant” “Rahul Kumar” #use double quotes if 1+ words
output
Hello Ashish Rahul
Hello Ashish Pant Rahul Kumar
greeting ()
{
echo "Hello $1"
echo "$2 How are you doing?"
}
greeting Ashish Pant
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:
Method 1 : Using return
add(){
sum=$(($1+$2))
return $sum
}
read -p "Enter an integer: " int1
read -p "Enter an integer: " int2
add $int1 $int2
echo "The result is: " $?
Output
Enter an integer: 4
Enter an integer: 9
The result is: 13
Note : Only Numerical values may be returned by above method
Method 2 : Using global variables
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.
read -p "Enter an integer: " int1
read -p "Enter an integer: " int2
add () {
sum=$(($1+$2)) # or ((sum=$1+$2))
str="addition completed!"
}
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
if [[ $arg1 != "" ]]; then
retval="BASH function with variable"
else
echo "No Argument"
fi
}
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.
Experiment No. 7.1
Write a shell script to print Diamond pattern.
Output
Experiment No. 7.2
Write a shell script to print Triangle pattern.
Output
Experiment No. 7.3
Write a shell script to print Square pattern.
Output
Experiment No. 7.4
Write a shell script to print Rectangle pattern.
Output
Experiment No. 7.5
Write a shell script to print hollow square.
Output