Professional Documents
Culture Documents
1 / 112
Vriables Bash Conditional
Bash Variable
2 / 112
Vriables Bash Conditional
Variables
◀ Local Variables
◀ Shell Variables
◀ Environment Variables
4 / 112
Vriables Bash Conditional
1 local variableReference=value
5 / 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
9 / 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
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
16 / 112
Vriables Bash Conditional
Example
17 / 112
Vriables Bash Conditional
Example
18 / 112
Vriables Bash Conditional
Argument List
19 / 112
Vriables Bash Conditional
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
21 / 112
Vriables Bash Conditional
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:
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:
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
$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
28 / 112
Vriables Bash Conditional
29 / 112
Vriables Bash Conditional
30 / 112
Vriables Bash Conditional
31 / 112
Vriables Bash Conditional
32 / 112
Vriables Bash Conditional
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
34 / 112
Vriables Bash Conditional
#!/usr/bin/bash
arg1="$1"
arg2="$2"
35 / 112
Vriables Bash Conditional
$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
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
◀ Positional Parameters
◀ Flags
◀ Loop Construct
◀ Shift Operator
38 / 112
Vriables Bash Conditional
Positional Parameters I
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.
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
44 / 112
Vriables Bash Conditional
Loop Construct II
45 / 112
Vriables Bash Conditional
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.
47 / 112
Vriables Bash Conditional
Shift Operator II
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
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 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.
51 / 112
Vriables Bash Conditional
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.
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
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
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
59 / 112
Vriables Bash Conditional
Relational Operators I
Relational Operators II
61 / 112
Vriables Bash Conditional
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
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
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
65 / 112
Vriables Bash Conditional
Logical Operators I
66 / 112
Vriables Bash Conditional
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
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
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
14 rightshift=$(( b>>1 ))
15 echo "Right Shift of b is $rightshift"
71 / 112
Vriables Bash Conditional
72 / 112
Vriables Bash Conditional
73 / 112
Vriables Bash Conditional
Bash Conditional
74 / 112
Vriables Bash Conditional
Bash If
75 / 112
Vriables Bash Conditional
76 / 112
Vriables Bash Conditional
Syntax of Bash If
77 / 112
Vriables Bash Conditional
Syntax of Bash If
78 / 112
Vriables Bash Conditional
Syntax of Bash If
79 / 112
Vriables Bash Conditional
Bash IF -z
80 / 112
Vriables Bash Conditional
Bash IF -s
81 / 112
Vriables Bash Conditional
Bash IF -n
82 / 112
Vriables Bash Conditional
Bash IF -f
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
#!/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
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
88 / 112
Vriables Bash Conditional
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
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
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
15 then
16 echo "valid traingle"
17 else
18 echo "not a valid traingle"
19 fi
20 fi
96 / 112
Vriables Bash Conditional
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
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
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
15 ((++i))
16 # end of while loop
17 done
103 / 112
Vriables Bash Conditional
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
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
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
109 / 112
Vriables Bash Conditional
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
111 / 112
Vriables Bash Conditional
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