Skip to end of metadata
Go to start of metadata

Click here for the lecture slide

Variables

 

We can use variables as in any programming languages. Their values are always stored as strings, but there are mathematical operators in the shell language that will convert variables to numbers for calculations. We do not need to declare a variable, just assigning a value to its reference will create it.

 

variables
Line 3 creates a variable called STR and assigns the string "Hello World!" to it. Then the value of this variable is retrieved by putting the '$' in at the beginning.

The BASH programming language does not type-cast its variables. This means that a variable can hold number data or character data (e.g. count=0 , count="Sunday"). Switching the TYPE of a variable can lead to confusion for the writer of the script or someone trying to modify it, so it is recommended to use a variable for only a single TYPE of data in a script.

Array

The Bash provides one-dimensional array variables. Any variable may be used as an array; the declare builtin will explicitly declare an array. There is no maximum limit on the size of an array, nor any requirement that members be indexed or assigned contiguously. Arrays are indexed using integers and are zero-based
array

 

In addition the following constructs are available:

 

${arr[*]} # All of the items in the array 
${!arr[*]} # All of the indexes in the array 
${#arr[*]} # Number of items in the array 
${#arr[0]} # Length of item zero 
array

 

Escape Character

The \ character is the bash escape character and it preserves the literal value of the next character that follows.

Single Quote, Double Quotes and Back Quote

 

Using single quote to show a string of characters will not allow variable resolution, while back quote is used to do command substitution.

 

Single Quote
Double Quotes
Back Quote

Manipulating String

Bash supports a number of string manipulation operations.

 

${#string} # gives the string length
${string:position} # extracts sub-string from $string at $position
${string:position:length} # extracts $length characters of sub-string from $string at $position
Manipulating String

Arithmetic Evaluation

The let statement can be used to do mathematical functions.

 

Arithmetic Evaluation
An arithmetic expression can be evaluated  by $[expression] or $((expression))

 

Arithmetic Expression
Arithmetic Expression

Flow Control

Flow control let us decide whether to perform an action or not, this decision is taken by evaluating an expression. The most basic form is as follow:

 

if [ expression ];
then
	statements
elif [ expression ];
then
	statements
else
	statements
fi
The elif (else if) and else sections are optional. Put spaces after [ and before ], and around the operators and operands.

Expression

 

An expression can be: String comparison, Numeric comparison, File operators and Logical operators and it is represented by [expression].
For string comparisons:
=   # compare if two strings are equal
!=  # compare if two strings are not equal
-n  # evaluate if string length is greater than zero
-z  # evaluate if string length is equal to zero

 
Examples:

[ s1 = s2 ]   (true if s1 same as s2, else false)
[ s1 != s2 ]   (true if s1 not same as s2, else false)
[ s1 ]   (true if s1 is not empty, else false)
[ -n s1 ]   (true if s1 has a length greater then 0, else false)
[ -z s2 ]   (true if s2 has a length of 0, otherwise false)

 

For number comparisons:

 

-eq  # compare if two numbers are equal
-ge  #  compare if one number is greater than or equal to a number
-le  #  compare if one number is less than or equal to a number
-ne  # compare if two numbers are not equal
-gt  # compare if one number is greater than another number
-lt  # compare if one number is less than another number

Examples:
 
[ n1 -eq n2 ]   (true if n1 same as n2, else false)
[ n1 -ge n2 ]   (true if n1greater than or equal to n2, else false)
[ n1 -le n2 ]   (true if n1 less than or equal to n2, else false)
[ n1 -ne n2 ]   (true if n1 is not same as n2, else false)
[ n1 -gt n2 ]   (true if n1 greater than n2, else false)
[ n1 -lt n2 ]   (true if n1 less than n2, else false)

 

For file operators:

 
-d  # check if path given is a directory
-f  # check if path given is a file
-e  # check if file name exists
-r  # check if read permission is set for file or directory
-s  # check if a file has a length greater than 0
-w  # check if write permission is set for a file or directory
-x  # check if execute permission is set for a file or directory


Examples:
[ -d fname ]   (true if fname is a directory, otherwise false)
[ -f fname ]   (true if fname is a file, otherwise false)
[ -e fname ]   (true if fname exists, otherwise false)
[ -s fname ]   (true if fname length is greater then 0, else false)
[ -r fname ]   (true if fname has the read permission, else false)
[ -w fname ]   (true if fname has the write permission, else false)
[ -x fname ]  (true if fname has the execute permission, else false)
Expression
Expression
Expression
Expression
Expression

 

Selection

 

Case statement is used to execute statements based on specific values. Often used in place of an if statement if there are a large number of conditions. Value used can be an expression and each set of statements must be ended by a pair of semicolons; a *) is used to accept any value not matched with list of values.

 

case $var in
	val1)
		statements;;
	val2)
		statements;;
	*)
		statements;;
esac
Selection

Loop/Repetition

The for structure is used when you are looping through a range of variables. 

 

for var in list
	do
		statements
	done
Statements are executed with var set to each value in the list.
Loop/Repeatition
Loop/Repeatition
Loop/Repeatition
The while structure is a looping structure. Used to execute a set of commands while a specified condition is true. The loop terminates as soon as the condition becomes false. If condition never becomes false, loop will never exit.
while expression
	do
		statements
	done
Loop/Repeatition

 

The continue command causes a jump to the next iteration of the loop, skipping all the remaining commands in that particular loop cycle, while the break command terminates the loop (breaks out of it).

 

Loop/Repeatition
Loop/Repeatition

 

The until structure is very similar to the while structure. The until structure loops until the condition is true. So basically it is "until this condition is true, do this".

until [expression]
	do
		statements
	done
Loop/Repeatition

Using Array with Loops

 

We can combine arrays with loops using a for loop. Below is the general syntax:

 

for x in ${arrayname[*]}
	do
		statements
	done
Array with Loops

Using Command Substitution with Loops

We can also combine command substitution with loops.

Command Substitution with Loops

Functions

 

Functions are nothing but small subroutines or subscripts within a Bash shell script. Basically it breaks up the program into smaller pieces. This improves overall script readability and ease of use. The general syntax for function is as follows:

 

function name(){
	Commands
}

 

You can call function by typing its name.

 

Functions
It is often the case that we would like the function to process some data for us. We supply the arguments directly after the function name. Within the function they are accessible as $1, $2, etc.
Functions
There are two types of variable in functions: global and local. Global is visible everywhere in the script, while local is only visible within that function. We need to use the keyword local in front of the variable the first time we set it's value.
Functions
  • No labels