You are on page 1of 112

Vriables Bash Conditional

"Linux Shell Programming"

Dr Vinesh Kumar Jain


Department of Computer Science & Engineering
Engineering College Ajmer
January 5, 2024

1 / 112
Vriables Bash Conditional

Bash Variable

Bash Variable in bash shell scripting is a memory location that


is used to contain a number, a character, a string, an array of
strings, etc.
◀ There are no data types for a variable. It can contain a
number, a character, a string, an array of strings, etc. and
be overridden with any other value.
◀ There is no need to declare a variable explicitly. When you
assign a value to the reference, variable declaration happens
implicitly.
Syntax
variableReference=value
Note : No space should be given before and after = , failing which
produces error “syntax error near unexpected token".

2 / 112
Vriables Bash Conditional

Demonstration of bash variables


1 #!/bin/bash
2 # number variable
3 num=10
4 echo $num
5 # character variable
6 ch='c'
7 echo $ch
8 # string variable
9 str="Hello Bob!"
10 echo $str
11 # array variable
12 arr=( "bash" "shell" "script" )
13 echo "${arr[0]}"
14 echo "${arr[1]}"
15 echo "${arr[2]}"
3 / 112
Vriables Bash Conditional

Variables

When a Shell is running there are three types of variables present:

◀ Local Variables
◀ Shell Variables
◀ Environment Variables

4 / 112
Vriables Bash Conditional

Bash Local Variable

Bash Local Variable is used to override a global bash variable, in


local scope, if already present with the same name.
Syntax
Following is the syntax of a bash local variable

1 local variableReference=value

5 / 112
Vriables Bash Conditional

Demonstration of bash Local Variables


1 #!/bin/bash
2 # bash variable
3 SHELL="Unix"
4 function bashShell {
5 # bash local variable
6 local SHELL="Bash"
7 echo $SHELL
8 }
9 echo $SHELL
10 bashShell
11 echo $SHELL
The first echo statement is in global scope and SHELL has value
of UNIX, but when bashShell function is called, the local variable
SHELL overrides the global variable and hence the echo $SHELL
echoed Bash.
6 / 112
Vriables Bash Conditional

Shell Variables
The Shell variables are specific to the current shell and used by the
Shell to function correctly. These variables are temporary, and
to make them permanent we can export them as environment
variables. Some of the common shell variables are:
◀ UID: Current logged in user’s ID
◀ HOSTNAME: The hostname of the computer at a partic-
ular time
◀ BASH_VERSINFO: Machine-readable form of bash ver-
sion
◀ BASH_VERSION: Human-readable output of bash ver-
sion
◀ DIRSTACK: Stack of directories available with ‘popd’ and
‘pushd’ command
◀ SHELLOPTS: Shell options can be set
7 / 112
Vriables Bash Conditional

Environment Variables
Environment Variables are system-wide available variables that
are available to any program or child process of the shell. Also,
the Shell Script defines the environment variables that are needed
to run the program. Some of the common Environment variables
are:
◀ MAIL: Mail directory of the user or the path to user’s mail-
box
◀ TEMP: Temporary files’ director location
◀ PWD: Current working directory
◀ OLDPWD: The previous working directory
◀ USER: The current user logged in
◀ LANG: The current language
◀ LOGNAME: User Name
◀ HOME: The home directory of the current user
◀ SHELL: The current shell
8 / 112
Vriables Bash Conditional

Commands for Shell and Environment Variables:

◀ env: We can use a custom environment to run another pro-


gram without modifying the existing environment.
◀ printenv: This will print all the environment variables of
the system.
◀ set: Used to set the environment and shell variables.
◀ exports: Export shell variables into environment variables.
◀ unset: Used to delete the environment and shell variables.
Print Shell and Environment variables
◀ printenv: Prints all the Environment variables.
◀ set: Prints Shell variables.

9 / 112
Vriables Bash Conditional

Creating the Shell variable


◀ To set a Shell variable run following command in Shell. This
will create a Shell variable that will be available in the current
session.
$TESTVAR=‘Hello!’
◀ We can also check our variable with the grep command.
$set | grep TESTVAR
Output will be like this. TESTVAR=‘Hello!’
◀ We can also see the value of a shell variable with the following
command.
$echo $TESTVAR
◀ As it is a Shell variable, so it will not be available for other
applications or child processes. We can even verify that it is
not an Environment variable.
$printenv | grep TESTVAR
There will be no output. It means it is not an Environment
variable. 10 / 112
Vriables Bash Conditional

Creating the Environment Variables


◀ Now, let’s export the Shell variable into an Environment vari-
able. Use the following command to do that.
$export TESTVAR
◀ This will turn our Shell variable into an Environment variable
and to verify that run the following command.
$printenv | grep TESTVAR
Output will be like this.
TESTVAR=’Hello!’
◀ Setting an Environment variable in a single step with this
command.
$export NEWVAR="Hello Env"
◀ We can verify using
$printenv | grep NEWVAR
◀ Output will be like this.
NEWVAR=Hello Env
11 / 112
Vriables Bash Conditional

Unsetting variables
◀ We can change an Environment variable into a Shell variable
again with this command.
$export -n TESTVAR
◀ It will remain a Shell variable but not an Environment vari-
able. Let’s verify that
$printenv | grep TESTVAR
◀ There will be no output but if we check it for the Shell vari-
able
$set | grep TESTVAR
◀ Output will be like this.
$TESTVAR=’Hello!’
◀ And if we want to completely unset that then use this com-
mand.
$unset TESTVAR
12 / 112
Vriables Bash Conditional

Example
#! /bin/bash
TESTVAR='HELLO!'
set|grep TESTVAR
echo $TESTVAR
printenv
printenv |grep TESTVAR
export TESTVAR
printenv |grep TESTVAR
echo "Making env variable to shell variable again"
export -n TESTVAR
printenv |grep TESTVAR.
echo "view shell variable"
set|grep TESTVAR
echo "Completely unsetting the TESTVAR"
unset TESTVAR
13 / 112
Vriables Bash Conditional

Command Line Arguments

Command Line Arguments


Command Line Arguments are used to provide input to a bash
shell script while executing the script.

◀ In bash shell programming we have maximum of nine argu-


ments to a shell script.
◀ Inside the shell script you can access the arguments as bash
variables $1, $2, $3... corresponding to first argument, sec-
ond argument, third argument etc., respectively.
◀ For multiple digit arguments we use curly braces as ${21}
for 21st argument.
◀ It is recommended that we should limit command line argu-
ments to nine for maintaining compatibility to other shells
and avoiding confusion.
14 / 112
Vriables Bash Conditional

Symbols in Command Line Argument

Variable Value
$0 The name of the shell script or command.
1−9 The indicated positional argument. For example,$1is the first argument.
$# The number of shell arguments.
$@ The value of each shell argument.
$* The values of all shell arguments.

15 / 112
Vriables Bash Conditional

Example

In this example we will read four arguments from command line,


and use them in our script.
#!/bin/bash
echo "Hello $1 !"
echo "We like your place, $2."
echo "Thank you for showing interest to learn $3 : $4."

16 / 112
Vriables Bash Conditional

Example

Following is a Bash shell script to print total number of command


line arguments passed to shell script.
1 #!/bin/bash
2 echo "$# arguments have been passed to this script,
,→ $0"

17 / 112
Vriables Bash Conditional

Example

In the following example, we will write a bash shell script that


uses more than nine arguments. Curly braces are used like $nn,
to access higher arguments (>9)
#!/bin/bash
echo "13th argument is ${13}"

18 / 112
Vriables Bash Conditional

Argument List

Arguments can be passed to a bash script during the time of


its execution, as a list, separated by space following the script
filename. This comes in handy when a script has to perform
different functions depending on the values of the input.
◀ Using Single Quote
◀ Using Double Quotes
◀ Escaping Special Characters
◀ Flags
◀ Environment Variables
◀ Last Argument Operator (!$)
◀ Pipe Operator (|)

19 / 112
Vriables Bash Conditional

Using Single Quote

For instance, let’s pass a couple of parameters to our script start.sh:


$./start.sh development 100
If the input list has arguments that comprise multiple words sep-
arated by spaces, they need to be enclosed in single quotes.

Example
For instance, in the above-mentioned example, if the first argu-
ment to be passed is development mode instead of development,
it should be enclosed in single quotes and passed as ‘development
mode’:
$./start.sh ‘development mode’ 100

20 / 112
Vriables Bash Conditional

Using Double Quotes

Arguments that require evaluation must be enclosed in double-


quotes before passing them as input.
Example
Consider a bash script copyFile.sh that takes in two arguments:
A file name and the directory to copy it to:

$./copyFile.sh abc.txt "$HOME"


Here, the $HOME variable gets evaluated to the user’s home di-
rectory, and the evaluated result is passed to the script.

21 / 112
Vriables Bash Conditional

Escaping Special Characters

If the arguments that need to be passed have special characters,


they need to be escaped with backslashes:
$./printStrings.sh abc a@1 cd\$ 1\*2
The characters $ and * do not belong to the safe set and hence
are escaped with backslashes. These rules for using single quotes,
double quotes, and escape characters remain the same for the
subsequent sections as well.

22 / 112
Vriables Bash Conditional

Flags

Arguments can also be passed to the bash script with the help of
flags. These flags are usually single character letters preceded by
a hyphen. The corresponding input value to the flag is specified
next to it separated by space.
Example
Let’s consider the following example of a user registration script,
userReg.sh which takes 3 arguments: username, full name, and
age:

$./userReg.sh -u abc -f Abc -a 25


Here, the input to the script is specified using the flags (u, f and a)
and the script processes this input by fetching the corresponding
values based on the flag.

23 / 112
Vriables Bash Conditional

Environment Variables I

Bash scripts can also be passed with the arguments in the form of
environment variables. This can be done in either of the following
ways:
◀ Specifying the variable value before the script execution com-
mand
◀ Exporting the variable and then executing the script

Example
Let’s look at the following example of a script processor.sh,
which takes two variables var1 and var2 as input. As mentioned
above these variables can be fed as input to the script:

$./var1=abc var2=c\#1 .\processor.sh

24 / 112
Vriables Bash Conditional

Environment Variables II

Here, we’re first specifying the values of the var1 and var2 vari-
ables before invoking the script execution, in the same command.
The same can also be achieved by exporting var1 and var2 as an
environment variable and then invoking the script execution:
$export var1=abc
$export var2=c\#1
.\processor.sh

25 / 112
Vriables Bash Conditional

Last Argument Operator (!$)


The last argument of the previous command, referred by !$ can
also be passed as an argument to a bash script.
Example
Let’s suppose we’re again copying files, and the destination is the
user home directory. Using the last argument operator, we can
pass the input to the script:

$cd $HOME
$./copyFile.sh abc.txt !$
In the first command, we navigate to the user home and when
the second command is invoked, !$ gets evaluated to the last
argument of the previous command which is $HOME and hence
the resultant command gets evaluated to:
$./copyFile.sh abc.txt $HOME
26 / 112
Vriables Bash Conditional

Pipe Operator (|)


Pipe operator (|) in combination with the xargs command can be
used to feed input to the bash scripts.
Example
Let’s revisit the earlier example of printStrings.sh script which
takes the input as a list of strings and prints them. Instead of
passing these strings as arguments in the command line, they can
be added inside a file. Then, this file, with the help of the pipe
operator and xargs command, can be used as the input:

$cat abc.txt | xargs printStrings.sh


Here, the cat command outputs the strings that have been added
in the file. These are then passed to the xargs command through
the pipe operator, which collects this list and passes it to the
script.
27 / 112
Vriables Bash Conditional

Changing Command-Line Arguments in Bash

Command-line arguments are values passed to a script or com-


mand when it’s executed. In Bash, these arguments are accessible
through the special variables $1, $2, $3, up to $9. In this case,
$1 represents the first argument, $2 represents the second argu-
ment, and so forth. These arguments are also contained in the
argument array, represented by the special variable $@.

28 / 112
Vriables Bash Conditional

Changing Command-Line Arguments in Bash

The set command enables us to change command-line arguments


in a flexible way. By using — with set, we can assign a new value
for each argument. When performing this task, we have a couple
of options:
◀ Explicitly specify the set of arguments
◀ Combine existing arguments with new ones

29 / 112
Vriables Bash Conditional

Explicitly specify the set of arguments I

◀ Assigning positional arguments with the set Com-


mand Here, we assign six positional arguments with the set
— command.
$ set -- arg1 arg2 arg3 arg4 arg5 arg6
We can view the current arguments and their values via $@:
$ echo "$@"
Output will be as follows of above command
arg1 arg2 arg3 arg4 arg5 arg6

◀ Changing positional arguments with the set Com-


mand To change the fourth argument, we can reset the ar-
gument list while also making use of array slicing:

30 / 112
Vriables Bash Conditional

Explicitly specify the set of arguments II

$ set -- "${@:1:3}" "new_arg4" "${@:5}"


$ echo "$@"
arg1 arg2 arg3 new_arg4 arg5 arg6
Again, set assigns new values to the positional parameters,
effectively changing the command-line arguments. In partic-
ular,
$@:1:3 retrieves the values of the first three positional pa-
rameters, which are arg1,arg2, and arg3. The $@:1:3 syn-
tax extracts a subset starting from position 1 and having a
length of 3. The result of $@:1:3 based on the values in $@
is a list of three elements: 1. arg1 2. arg2 3.arg3
Then, we assign the value new_arg4 as the fourth positional
parameter.

31 / 112
Vriables Bash Conditional

Explicitly specify the set of arguments III

Finally, $@:5 retrieves all the positional parameters from the


fifth position until the end. The result is a list containing all
the parameters from arg5 onward.
◀ Removing positional arguments with the set Com-
mand

To remove the fourth positional argument, we can re-list the


arguments as desired, skipping the fourth element in $@:
$ set -- "${@:1:3}" "${@:5}"
$ echo "$@"
Output will be like this arg1 arg2 arg3 arg5 arg6

32 / 112
Vriables Bash Conditional

Explicitly specify the set of arguments IV

Note
In general, by using array slicing and concatenating elements,
we can rearrange the set of arguments, collectively, in any way
desired.

33 / 112
Vriables Bash Conditional

Combine existing arguments with new ones I

◀ A common approach to changing command-line arguments


within a script is to assign them to variables
◀ Therefore, instead of directly modifying the arguments, we
copy their values in variables and modify these variables.
◀ Thus, we can manipulate the arguments without affecting the
original command-line argument variables and their values.
◀ In fact, this approach of preserving the original script and
leaving its arguments intact is considered a best practice.
Let’s illustrate the idea with a script, named modify_args.sh:

34 / 112
Vriables Bash Conditional

Combine existing arguments with new ones II

#!/usr/bin/bash
arg1="$1"
arg2="$2"

# Modify the variables


arg1='new_arg1'
arg2='new_arg2'

echo "Unmodified arguments: $@"


echo "Modified first argument: $arg1"
echo "Modified second argument: $arg2"

35 / 112
Vriables Bash Conditional

Combine existing arguments with new ones III

We assign the first two arguments passed to the script to the


variables arg1 and arg2, respectively. Then, these variables are
modified, and the original arguments as well as the new values
are echoed by the script.

$chmod +x modify_args.sh
$./modify_args.sh one two
Output
Unmodified arguments: one two
Modified first argument: new_arg1
Modified second argument: new_arg2

36 / 112
Vriables Bash Conditional

Combine existing arguments with new ones IV

Note
We notice that the unmodified arguments are one and two, while
variables arg1 and arg2 have taken on the new values assigned
in the script. This is a common way to modify and use command-
line arguments while preserving the original versions passed on to
the script.

37 / 112
Vriables Bash Conditional

Use of Command Line Arguments in a Bash Script I

◀ Positional Parameters
◀ Flags
◀ Loop Construct
◀ Shift Operator

38 / 112
Vriables Bash Conditional

Positional Parameters I

◀ Arguments passed to a script are processed in the same order


in which they’re sent.
◀ The indexing of the arguments starts at one, and the first
argument can be accessed inside the script using $1.
◀ Similarly, the second argument can be accessed using $2, and
so on.
◀ The positional parameter refers to this representation of the
arguments using their position.

39 / 112
Vriables Bash Conditional

Positional Parameters II

1 #!/bin/bash
2 echo "Username: $1";
3 echo "Age: $2";
4 echo "Full Name: $3";

40 / 112
Vriables Bash Conditional

Flags I

Flag
Using flags is a common way of passing input to a script. When
passing input to the script, there’s a flag (usually a single letter)
starting with a hyphen (-) before each argument.

◀ Let’s take a look at the cmdf.sh script, which takes three


arguments: username (-u), age (-a), and full name (-f).
◀ The getopts function reads the flags in the input, and OP-
TARG refers to the corresponding values:

41 / 112
Vriables Bash Conditional

Flags II

1 #!/bin/bash
2 while getopts u:a:f: flag
3 do
4 case "${flag}" in
5 u) username=${OPTARG};;
6 a) age=${OPTARG};;
7 f) fullname=${OPTARG};;
8 esac
9 done
10 echo "Username: $username";
11 echo "Age: $age";
12 echo "Full Name: $fullname";

42 / 112
Vriables Bash Conditional

Flags III

Note
Here we’re using the getopts function to parse the flags provided
as input, and the case block to assign the value specified to the
corresponding variable.

43 / 112
Vriables Bash Conditional

Loop Construct I

◀ Positional parameters, while convenient in many cases, can’t


be used when the input size is unknown.
◀ The use of a loop construct comes in handy in these situa-
tions.
◀ The variable $@ is the array of all the input parameters.
Using this variable within a for loop, we can iterate over the
input and process all the arguments passed.

44 / 112
Vriables Bash Conditional

Loop Construct II

Let’s take an example of the script cmdloop.sh, which prints all


the usernames that have been passed as input:
1 #!/bin/bash
2 i=1;
3 for user in "$@"
4 do
5 echo "Username - $i: $user";
6 i=$((i + 1));
7 done

45 / 112
Vriables Bash Conditional

Loop Construct III

Note
In the above example, we’re iterating the user variable over the
entire array of input parameters. This iteration starts at the
first input argument, Vinesh, and runs until the last argument,
Dinesh, even though the size of the input is unknown.

46 / 112
Vriables Bash Conditional

Shift Operator I

Shift Operator
Shift operator in bash (syntactically shift n, where n is the num-
ber of positions to move) shifts the position of the command line
arguments. The default value for n is one if not specified.

◀ The shift operator causes the indexing of the input to start


from the shifted position.
◀ In other words, when this operator is used on an array input,
the positional parameter $1 changes to the argument reached
by shifting n positions to the right from the current argument
bound to positional parameter $1.

47 / 112
Vriables Bash Conditional

Shift Operator II

Consider an example script that determines whether the input is


odd or even:
$./parityCheck.sh 13 18 27 35 44 52 61 79 93

Understanding
From the above discussion on the positional parameter, we now
know that $1 refers to the first argument, which is 13. Using
the shift operator with input 1 (shift 1) causes the indexing to
start from the second argument. That is, $1 now refers to the
second argument (18). Similarly, calling shift 2 will then cause
the indexing to start from the fourth argument (35).

48 / 112
Vriables Bash Conditional

Shift Operator III

Instead of using the $@ variable and iterating over it, we’ll now
use the shift operator. The $ variable returns the input size:
1 #!/bin/bash
2 i=1;
3 j=$#;
4 while [ $i -le $j ]
5 do
6 echo "Username - $i: $1";
7 i=$((i + 1));
8 shift 1;
9 done

49 / 112
Vriables Bash Conditional

Shift Operator IV

Note
In this example, we’re shifting the positional parameter in each
iteration by one until we reach the end of the input. Therefore,
$1 refers to the next element in the input each time.

50 / 112
Vriables Bash Conditional

Exit and Exit status of a command I

Exit Status
Each Linux or Unix command will return a exit code while ter-
minating. and this exit code is a numeric value varies from 0 to
255. And it also be called an exit code or exit status.

◀ If a Linux command or bash shell script terminates normally,


and it will return a exit code as number 0. otherwise, it will
return an non-zero value.
◀ If we want to get exit code or exit status of a linux command,
and you can run echo $? command to get the status of
executed command.

51 / 112
Vriables Bash Conditional

Various exit codes in Linux shell I

Note
Success is represented with exit 0; failure is normally indicated
with a non-zero exit-code. This value can indicate different rea-
sons for failure.

Exit code Meaning of the code


0 Command executed with no errors
1 Code for generic errors
2 Incorrect command (or argument) usage
126 Permission denied (or) unable to execute
127 Command not found, or PATH error
128+n Command terminated externally by passing signals, or it
encountered a fatal error, The n tells us which signal was
received
130 Termination by Ctrl+C or SIGINT (termination code
128+2 or keyboard interrupt)
143 Termination by SIGTERM (128+15 default termination)
255/* Exit code exceeded the range 0-255, hence wrapped up
52 / 112
Vriables Bash Conditional

Examples

53 / 112
Vriables Bash Conditional

Examples I

1 #!/bin/bash
2 touch /home/vinesh/exitcode.txt
3 ecode=$?
4 if [ $ecode -eq 0 ]
5 then
6 echo "file created!"
7 else
8 echo "failed to create file!"
9 fi

54 / 112
Vriables Bash Conditional

Examples II

exit in IF statement
We can also use the exit status in the conditional IF statement
in as in above shell script. For example, We created a file using
touch command, and then we want to check if this file is created
successfully. We can use the exit status of the above touch
command, if the exit code is 0, it indicates that the file is created.

55 / 112
Vriables Bash Conditional

Operators

There are 5 basic operators in bash/shell scripting:


◀ Arithmetic Operators
◀ Relational Operators
◀ Boolean Operators
◀ Bitwise Operators
◀ File Test Operators

56 / 112
Vriables Bash Conditional

Arithmetic Operators
These operators are used to perform normal arithmetics/mathe-
matical operations. There are 7 arithmetic operators:
◀ Addition(+): Binary operation used to add two operands.
◀ Subtraction (-): Binary operation used to subtract two operands.
◀ Multiplication (*): Binary operation used to multiply two
operands.
◀ Division (/): Binary operation used to divide two operands.
◀ Modulus (%): Binary operation used to find remainder of
two operands.
◀ Increment Operator (++): Unary operator used to increase
the value of operand by one.
◀ Decrement Operator (- -): Unary operator used to decrease
the value of a operand by one
57 / 112
Vriables Bash Conditional

Example of Arithmetic Operators I

1 #!/bin/bash
2 read -p 'Enter a : ' a
3 read -p 'Enter b : ' b
4 add=$((a + b))
5 echo "Addition of a and b are" $add
6 sub=$((a - b))
7 echo "Subtraction of a and b are" $sub
8 mul=$((a * b))
9 echo "Multiplication of a and b are" $mul
10 div=$((a / b))
11 echo "division of a and b are" $div
12 mod=$((a % b))
13 echo "Modulus of a and b are" $mod
14 ((++a))
58 / 112
Vriables Bash Conditional

Example of Arithmetic Operators II

15 echo "Increment operator when applied on "a" results


,→ into a =" $a
16 ((--b))
17 echo "Decrement operator when applied on "b" results
,→ into b =" $b

59 / 112
Vriables Bash Conditional

Relational Operators I

Relational operators are those operators which define the relation


between two operands. They give either true or false depending
upon the relation. They are of 6 types:
◀ ==’ Operator: Double equal to operator compares the two
operands. Its returns true is they are equal otherwise returns
false.
◀ ‘ !=’ Operator: Not Equal to operator return true if the two
operands are not equal otherwise it returns false.
◀ ‘<‘ Operator: Less than operator returns true if first operand
is less than second operand otherwise returns false.
◀ ‘<=’ Operator: Less than or equal to operator returns true
if first operand is less than or equal to second operand oth-
erwise returns false
60 / 112
Vriables Bash Conditional

Relational Operators II

◀ ‘>’ Operator: Greater than operator return true if the first


operand is greater than the second operand otherwise return
false.
◀ >=’ Operator: Greater than or equal to operator returns
true if first operand is greater than or equal to second operand
otherwise returns false

61 / 112
Vriables Bash Conditional

Example of Relational Operators I

1 #!/bin/bash
2 read -p 'Enter a : ' a
3 read -p 'Enter b : ' b
4 if(( $a==$b ))
5 then
6 echo "a is equal to b."
7 else
8 echo "a is not equal to b."
9 fi
10 if(( $a!=$b ))
11 then
12 echo "a is not equal to b."
13 else
14 echo "a is equal to b."
62 / 112
Vriables Bash Conditional

Example of Relational Operators II

15 fi
16 if(( $a<$b ))
17 then
18 echo "a is less than b."
19 else
20 echo "a is not less than b."
21 fi
22 if(( $a<=$b ))
23 then
24 echo "a is less than or equal to b."
25 else
26 echo "a is not less than or equal to b."
27 fi
28 if(( $a>$b ))
63 / 112
Vriables Bash Conditional

Example of Relational Operators III

29 then
30 echo "a is greater than b."
31 else
32 echo "a is not greater than b."
33 fi
34 if(( $a>=$b ))
35 then
36 echo "a is greater than or equal to b."
37 else
38 echo "a is not greater than or equal to b."
39 fi

64 / 112
Vriables Bash Conditional

Example of Relational Operators IV

65 / 112
Vriables Bash Conditional

Logical Operators I

They are also known as boolean operators. These are used to


perform logical operations. They are of 3 types:
◀ This is a binary operator, which returns true if both the
operands are true otherwise returns false.
◀ This is a binary operator, which returns true is either of the
operand is true or both the operands are true and return
false if none of then is false.
◀ This is a unary operator which returns true if the operand is
false and returns false if the operand is true.

66 / 112
Vriables Bash Conditional

Example of Logical Operators I

1 #!/bin/bash
2 read -p 'Enter a : ' a
3 read -p 'Enter b : ' b
4 if [[ $a == "true" && $b == "true" ]];
5 then
6 echo "Both are true."
7 else
8 echo "Both are not true."
9 fi
10 if [[ $a == "true" || $b == "true" ]];
11 then
12 echo "Atleast one of them is true."
13 else
14 echo "None of them is true."
67 / 112
Vriables Bash Conditional

Example of Logical Operators II

15 fi
16 if [[ ! $a == "true" ]];
17 then
18 echo "a was initially false."
19 else
20 echo "a was initially true."
21 fi

68 / 112
Vriables Bash Conditional

Bitwise Operators I
A bitwise operator is an operator used to perform bitwise opera-
tions on bit patterns. They are of 6 types:
◀ Bitwise & operator performs binary AND operation bit by
bit on the operands.
◀ Bitwise | operator performs binary OR operation bit by bit
on the operands.
◀ Bitwise ôperator performs binary XOR operation bit by bit
on the operands.
◀ Bitwise operator performs binary NOT operation bit by bit
on the operand.
◀ Left Shift («): This operator shifts the bits of the left operand
to left by number of times specified by right operand.
◀ Right Shift (»): This operator shifts the bits of the left
operand to right by number of times specified by right operand.
69 / 112
Vriables Bash Conditional

Example of Bitwise Operators I

1 #!/bin/bash
2 read -p 'Enter a : ' a
3 read -p 'Enter b : ' b
4 bitwiseAND=$(( a&b ))
5 echo "Bitwise AND of a and b is $bitwiseAND"
6 bitwiseOR=$(( a|b ))
7 echo "Bitwise OR of a and b is $bitwiseOR"
8 bitwiseXOR=$(( a^b ))
9 echo "Bitwise XOR of a and b is $bitwiseXOR"
10 bitiwiseComplement=$(( ~a ))
11 echo "Bitwise Compliment of a is $bitiwiseComplement"
12 leftshift=$(( a<<1 ))
13 echo "Left Shift of a is $leftshift"

70 / 112
Vriables Bash Conditional

Example of Bitwise Operators II

14 rightshift=$(( b>>1 ))
15 echo "Right Shift of b is $rightshift"

71 / 112
Vriables Bash Conditional

File Test Operator I

These operators are used to test a particular property of a file.


◀ -b operator: This operator check whether a file is a block
special file or not. It returns true if the file is a block special
file otherwise false.
◀ -c operator: This operator checks whether a file is a character
special file or not. It returns true if it is a character special
file otherwise false.
◀ -d operator: This operator checks if the given directory exists
or not. If it exists then operators returns true otherwise false.
◀ -e operator: This operator checks whether the given file exists
or not. If it exits this operator returns true otherwise false.

72 / 112
Vriables Bash Conditional

File Test Operator II

◀ -r operator: This operator checks whether the given file has


read access or not. If it has read access then it returns true
otherwise false.
◀ -w operator: This operator check whether the given file has
write access or not. If it has write then it returns true oth-
erwise false.
◀ -x operator: This operator check whether the given file has
execute access or not. If it has execute access then it returns
true otherwise false.
◀ -s operator: This operator checks the size of the given file.
If the size of given file is greater than 0 then it returns true
otherwise it is false.

73 / 112
Vriables Bash Conditional

Bash Conditional

Bash Conditional Statements are used to execute a block of state-


ments based on the result of a condition.
◀ Bash If
◀ Bash If Else
◀ Bash Elif
◀ Bash Case

74 / 112
Vriables Bash Conditional

Bash If

Bash IF statement is used for conditional branching in the se-


quential flow of execution of statements.

75 / 112
Vriables Bash Conditional

Options for IF statement in Bash Scripting

if statement can accept options to perform a specific task. These


options are used for file operations, string operations, etc. In this
topic, we shall provide examples for some mostly used options.
◀ if -z (to check if string has zero length)
◀ if -s (to check if file size is greater than zero)
◀ if -n (to check if string length is not zero)
◀ if -f (to check if file exists and is a regular file)

76 / 112
Vriables Bash Conditional

Syntax of Bash If

Bash If statement syntax is


if [ expression ];
# ^ ^ ^ please note these spaces
then
statement(s)
fi
Note
Observe the mandatory spaces required, in the first line, marked
using arrows. Also the semicolon at the end of first line. And if
conditional statement ends with fi.

77 / 112
Vriables Bash Conditional

Syntax of Bash If

◀ The syntax to include multiple conditions with AND opera-


tor is
if [ expression ] && [ expression_2 ];
then
statement(s)
fi
◀ The syntax to include multiple conditions with OR operator
is
if [ expression ] || [ expression_2 ];
then
statement(s)
fi

78 / 112
Vriables Bash Conditional

Syntax of Bash If

For compound expressions, following if syntax is allowed. Please


observe that the condition has double square brackets.
if [[ expression_1 && expression_2 || expression_3 ]];
then
statement(s)
fi

79 / 112
Vriables Bash Conditional

Bash IF -z

if statement when used with option z, returns true if the length


of the string is zero. Following example proves the same.
#!/bin/bash
if [ -z "" ];
then
echo "zero length string"
fi
if [ -z "hello" ];
then
echo "hello is zero length string"
else
echo "hello is not zero length string"
fi

80 / 112
Vriables Bash Conditional

Bash IF -s

Bash if statement when used with option s, returns true if size


of the file is greater than zero.
if [ -s /home/tutorialkart/sample.txt ];
then
echo "Size of sample.txt is greater than zero"
else
echo "Size of sample.txt is zero"
fi

81 / 112
Vriables Bash Conditional

Bash IF -n

Bash if statement when used with option n, returns true if the


length ofthe string is greater than zero.
#!/bin/bash
if [ -n "learn" ];
then
echo "learn is non-zero length string"
fi
if [ -n "hello" ];
then
echo "hello is non-zero length string"
else
echo "hello is zero length string"
fi

82 / 112
Vriables Bash Conditional

Bash IF -f

Bash if statement when used with option f, returns true if file


exists and is a regular file. Following example proves the same.
#!/bin/bash

if [ -f /home/tutorialkart/sample.txt ];
then
echo "sample.txt - File exists."
else
echo "sample.txt - File does not exist."
fi

83 / 112
Vriables Bash Conditional

Example 1 – Bash IF
In the following example, we demonstrate the usage of if state-
ment with a simple scenario of comparing two strings.
#!/bin/bash

# if condition is true
if [ "hello" == "hello" ];
then
echo "hello equals hello"
fi

# if condition is false
if [ "hello" == "bye" ];
then
echo "hello equals bye"
fi
84 / 112
Vriables Bash Conditional

Example 1 – Bash IF Comparing Strings

#!/bin/bash
# if condition is true
if [ "hello" == "hello" ];
then
echo "hello equals hello"
fi
# if condition is false
if [ "hello" == "bye" ];
then
echo "hello equals bye"
fi
Note
Observe the spaces provided after if [ string literal “hello” and ==

85 / 112
Vriables Bash Conditional

Example 2 – Bash IF – Compare Numbers I

In the following example, we will compare numbers using if state-


ment.

1 #!/bin/bash
2 # if condition (greater than) is true
3 if [ 8 -gt 7 ];
4 then
5 echo "is 8 greater than 7 : true "
6 fi
7 # if condition (greater than) is false
8 if [ 7 -gt 8 ];
9 then
10 echo "is 7 greater than 8 : false "
11 fi
86 / 112
Vriables Bash Conditional

Example 2 – Bash IF – Compare Numbers II

12 # if condition (less than) is true


13 if [ 7 -lt 8 ];
14 then
15 echo "is 7 lesser than 8 : true "
16 fi
17

18 # if condition (lesser than) is false


19 if [ 8 -lt 7 ];
20 then
21 echo "is 8 lesser than 7 : false "
22 fi
23 # if condition (equal to) is true
24 if [ 8 -eq 8 ];
25 then
87 / 112
Vriables Bash Conditional

Example 2 – Bash IF – Compare Numbers III

26 echo "is 8 equals 8 : true "


27 fi
28 # if condition (equal to) is false
29 if [ 7 -eq 8 ];
30 then
31 echo "is 7 equals 8 : false "
32 fi

88 / 112
Vriables Bash Conditional

Example 3 – Using AND in IF Expression


In this example, we shall learn to use AND operator && to com-
bine multiple conditions and form an expression (compound con-
dition).
1 #!/bin/bash
2 # TRUE && TRUE
3 if [ "hello" == "hello" ] && [ 1 -eq 1 ];
4 then
5 echo "if 1"
6 fi
7 # TRUE && FALSE
8 if [ "hello" == "hello" ] && [ 1 -gt 2 ];
9 then
10 echo "if 2"
11 fi
89 / 112
Vriables Bash Conditional

Example 4 – Using OR in IF Expression


In this example, we shall learn to use OR operator || to combine
multiple conditions and form an expression (compound condi-
tion).
1 #!/bin/bash
2 # TRUE || FALSE
3 if [ "hello" == "hello" ] || [ 1 -eq 3 ];
4 then
5 echo "if 1"
6 fi
7 # FALSE || FALSE
8 if [ "hello" == "hi" ] || [ 1 -gt 2 ];
9 then
10 echo "if 2"
11 fi
90 / 112
Vriables Bash Conditional

Example 5 – Bash IF with Multiple Conditions


In this example, we shall learn to include multiple conditions
combined with AND and OR forming a single expression.
1 #!/bin/bash
2 # FALSE && TRUE || FALSE || TRUE evaluates to TRUE
3 if [[ 8 -eq 11 && "hello" == "hello" || 1 -eq 3 || 1
,→ -eq 1 ]];
4 then
5 echo "if 1"
6 fi
7 # FALSE && TRUE || FALSE evaluates to FALSE
8 if [[ 8 -eq 11 && "hello" == "hello" || 1 -eq 3 ]];
9 then
10 echo "if 2"
11 fi
91 / 112
Vriables Bash Conditional

Shell script to find the greatest of three numbers


1 #!/bin/bash
2 echo "Enter Num1"
3 read num1
4 echo "Enter Num2"
5 read num2
6 echo "Enter Num3"
7 read num3
8 if [ $num1 -gt $num2 ] && [ $num1 -gt $num3 ]
9 then
10 echo $num1
11 elif [ $num2 -gt $num1 ] && [ $num2 -gt $num3 ]
12 then
13 echo $num2
14 else
15 echo $num3
16 fi 92 / 112
Vriables Bash Conditional

Shell script to find the greatest of three numbers

1 #!/bin/bash
2 read a
3 read b
4 read c
5 if (($a>$b && $a>$c))
6 then
7 echo "$a is the largest Number"
8 elif (($b>$a && $b>$c))
9 then
10 echo "$b is the largest Number"
11 else
12 echo "$c is the largest Number"
13 fi

93 / 112
Vriables Bash Conditional

Shell script to check the year is the leap year or not

1 #!/bin/sh
2 echo "Enter the year"
3 read year
4 x=`expr $year % 400`
5 y=`expr $year % 100`
6 z=`expr $year % 4`
7 if [ $x -eq 0 ] || [ $y -ne 0 ] && [ $z –eq 0]
8 then
9 echo " Entered year - $year is a leap year"
10 else
11 echo "Entered year - $year is not a leap year "
12 fi

94 / 112
Vriables Bash Conditional

Shell script to find whether triangle is valid or not I

1 #!/bin/sh
2 echo "enter angle A"
3 read A
4 echo "enter angle B"
5 read B
6 echo "enter angle C"
7 read C
8 # sum all three angles
9 d=$((A+B+C))
10 if [ $A -eq 0 -o $B -eq 0 -o $C -eq 0 ]
11 then
12 echo "Enter angles greater than zero"
13 else
14 if [ $d == 180 ];
95 / 112
Vriables Bash Conditional

Shell script to find whether triangle is valid or not II

15 then
16 echo "valid traingle"
17 else
18 echo "not a valid traingle"
19 fi
20 fi

96 / 112
Vriables Bash Conditional

Shell script to find whether triangle is valid or not I

1 #!/bin/bash
2

3 if [ -z "" ];
4 then
5 echo "zero length string"
6 fi
7 if [ -z "hello" ];
8 then
9 echo "hello is zero length string"
10 else
11 echo "hello is not zero length string"
12 fi

97 / 112
Vriables Bash Conditional

While Loop in Shell Script I


◀ In following code command1 to command3 will be executed
repeatedly till condition is true. The argument for a while
loop can be any boolean expression. Infinite loops occur
when the conditional never evaluates to false.

1 while [condition - should evaluate to TRUE or FALSE]


2 do
3 command 1
4 command 2
5 command 3
6 done
◀ Here is the while loop one-liner syntax:
1 while [ condition ]; do commands; done
2 while control-command; do COMMANDS; done
98 / 112
Vriables Bash Conditional

While loop for even and odd number from 1 to 10. I

1 # Take user input


2 echo "Enter a number"
3 read n
4 echo "Even Numbers - "
5 i=1
6 # -le means less than or equal to
7 while [ $i -le $n ]
8 do
9 # arithmetic operations is performed with 'expr'
10 rs=`expr $i % 2`
11 if [ $rs == 0 ]
12 then
13 echo " $i"
14 # end of if loop
99 / 112
Vriables Bash Conditional

While loop for even and odd number from 1 to 10. II

15 fi
16 # incrementing i by one
17 ((++i))
18 # end of while loop
19 done
20 # Now printing odd numbers
21 echo "Odd Numbers - "
22 i=1
23 while [ $i -le $n ]
24 do
25 rs=`expr $i % 2`
26 if [ $rs != 0 ]
27 then
28 echo " $i"
100 / 112
Vriables Bash Conditional

While loop for even and odd number from 1 to 10. III

29 fi
30 ((++i))
31 done

101 / 112
Vriables Bash Conditional

While loop for table of a given number I

1 #!/bin/bash
2 # Input from user
3 echo "Enter the number -"
4 read n
5 # initializing i with 1
6 i=1
7 # Looping i, i should be less than
8 # or equal to 10
9 while [ $i -le 10 ]
10 do
11 res=`expr $i \* $n`
12 # printing on console
13 echo "$n * $i = $res"
14 # incrementing i by one
102 / 112
Vriables Bash Conditional

While loop for table of a given number II

15 ((++i))
16 # end of while loop
17 done

103 / 112
Vriables Bash Conditional

While loop to calculate factorial I

1 #!/bin/bash
2 # A shell script to find the factorial of a number
3 read -p "Enter a number" num
4 fact=1
5 while [ $num -gt 1 ]
6 do
7 fact=$((fact*num))
8 num=$((num-1))
9 done
10 echo $fact

104 / 112
Vriables Bash Conditional

While loop to find sum of all even numbers upto 10 I

1 #! /bin/bash
2 echo enter limit
3 read n
4 i=2
5 while [ $i -le $n ]
6 do
7 sum=$((sum+i))
8 i=$((i+2))
9 done
10 echo $sum

105 / 112
Vriables Bash Conditional

While loop to print sum of digit of any number I

1 echo "Enter a number"


2 read num
3 sum=0
4 while [ $num -gt 0 ]
5 do
6 mod=`expr $num % 10` #It will split each digits
7 sum=`expr $sum + $mod` #Add each digit to sum
8 num=`expr $num / 10` #divide num by 10.
9 done
10 echo $sum

106 / 112
Vriables Bash Conditional

case Statement I

case Statement
The case statement tests the input value until it finds the corre-
sponding pattern and executes the command linked to that input
value. Thus, it is an excellent choice for creating menus where
users select an option which triggers a corresponding action.

1 case $variable in
2 pattern-1)
3 commands;;
4 pattern-2)
5 commands;;
6 pattern-3)
7 commands;;
8 pattern-N)
107 / 112
Vriables Bash Conditional

case Statement II
9 commands;;
10 *)
11 commands;;
12 esac
◀ case: The statement starts with the case keyword followed
by the $variable and the in keyword. The statement ends
with the case keyword backwards - esac.
◀ $variable:The script compares the input $variable against
the patterns in each clause until it finds a match.
◀ Patterns:
A pattern and its commands make a clause, which ends with
;;.
Patterns support special characters.
The ) operator terminates a pattern list.
108 / 112
Vriables Bash Conditional

case Statement III

The | operator separates multiple patterns.


The script executes the commands corresponding to the first
pattern matching the input $variable.
The asterisk * symbol defines the default case, usually in the
final pattern.
◀ Exit Status:The script has two exit statuses:
0. The return status when the input matches no pattern.
Executed command status. If the command matches the in-
put variable to a pattern, the executed command exit status
is returned.

109 / 112
Vriables Bash Conditional

case Statement Example I

1 #!/bin/sh
2 echo "Please talk to me ..."
3 while :
4 do
5 read INPUT_STRING
6 case $INPUT_STRING in
7 hello)
8 echo "Hello yourself!"
9 ;;
10 bye)
11 echo "See you again!"
12 break
13 ;;
14 *)
110 / 112
Vriables Bash Conditional

case Statement Example II

15 echo "Sorry, I don't understand"


16 ;;
17 esac
18 done
19 echo
20 echo "That's all folks!"

111 / 112
Vriables Bash Conditional

case Check Character Type Example I

1 #!/bin/bash
2 echo "Enter a character:"
3 read var
4 case $var in
5 [[:lower:]]) echo "You entered a lowercase character.";;
6 [[:upper:]]) echo "You entered an uppercase character.";;
7 [0-9]) echo "You entered a digit.";;
8 ?) echo "You entered a special character.";;
9 *) echo "You entered multiple characters.";;
10 esac

112 / 112

You might also like