Hello, continue with the Shell programming series, this article we will learn about conditional statements, arrays, loops, functions …
1. Conditional statement
- If you already know conditional statements in other programming languages, the same is true for Shell. It is different only in syntax.
- There are 5 conditional statements in Shell programming:
- if statement
- if-else statement
- if..elif..else..fi statement
- if..then..else..if..then..fi..fi .. (Nested if)
- switch statement
Syntax
If statement
1 2 3 4 5 |
if [ expression ] then statement fi |
if-else statement
1 2 3 4 5 6 7 |
if [ expression ] then statement1 else statement2 fi |
if..elif..else..fi statement
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
if [ expression1 ] then statement1 statement2 . . elif [ expression2 ] then statement3 statement4 . . else statement5 fi |
if..then..else..if..then..fi..fi .. (Nested if)
1 2 3 4 5 6 7 8 9 10 11 12 13 |
if [ expression1 ] then statement1 statement2 . else if [ expression2 ] then statement3 . fi fi |
switch statement
1 2 3 4 5 |
case in Pattern 1) Statement 1;; Pattern n) Statement n;; esac |
2. Array in Shell
- In the previous article we learned about shell variables used to store a value, called a scalar variable. Shell also supports another variable called array variable . Variable naming rules also apply to array naming.
Array definition
- Define:
array_name[index]=value
- array_name: The name of the array
- index: is the index of the item in the array
- value: value at that index
- For example:
1 2 3 4 5 6 |
NAME[0]="Zara" NAME[1]="Qadir" NAME[2]="Mahnaz" NAME[3]="Ayan" NAME[4]="Daisy" |
- If we are using KornShell array initialization syntax:
set -A array_name value1 value2 ... valuen
- If we are using BashShell the syntax of initializing arrays:
array_name=(value1 ... valuen)
Accessing array values
- Syntax for accessing the value of an array:
${array_name[index]}
- Consider the following example, create file test.sh :
1 2 3 4 5 6 7 8 9 10 |
#!/bin/bash NAME[0]="Zara" NAME[1]="Qadir" NAME[2]="Mahnaz" NAME[3]="Ayan" NAME[4]="Daisy" echo "First Index: ${NAME[0]}" echo "Second Index: ${NAME[1]}" |
- Example results above:
1 2 3 4 |
$./test.sh First Index: Zara Second Index: Qadir |
- We can also access all items in the array with the following syntax:
1 2 3 |
${array_name[*]} ${array_name[@]} |
- See the following example:
1 2 3 4 5 6 7 8 9 10 |
#!/bin/bash NAME[0]="Zara" NAME[1]="Qadir" NAME[2]="Mahnaz" NAME[3]="Ayan" NAME[4]="Daisy" echo "First Method: ${NAME[*]}" echo "Second Method: ${NAME[@]}" |
- Result:
1 2 3 4 |
$./test.sh First Method: Zara Qadir Mahnaz Ayan Daisy Second Method: Zara Qadir Mahnaz Ayan Daisy |
3. The loop
- The loop is a powerful programming tool that allows us to execute a script on a continuous basis. We will explore the loops Shell supports for programmers:
- The while loop
- The for loop
- The until loop
- The select loop
- It is possible to change the state of the loop using the break, continue statement as in other languages.
- We can also use nested loops.
While loop
- First, we will learn about the while loop. About using similar languages like C ++, java …
- Syntax:
1 2 3 4 5 |
while command do Statement(s) to be executed if command is true done |
- Example: Print out integers smaller than 10.
1 2 3 4 5 6 7 8 9 |
#!/bin/bash a=0 while [ $a -lt 10 ] do echo $a a=`expr $a + 1` done |
- Result:
1 2 3 4 5 6 7 8 9 10 11 |
0 1 2 3 4 5 6 7 8 9 |
For loop
- The second loop we will find out is the For loop.
- Syntax:
1 2 3 4 5 |
for var in word1 word2 ... wordN do Statement(s) to be executed for every word. done |
- For example:
1 2 3 4 5 6 7 |
#!/bin/bash for var in 0 1 2 3 4 5 6 7 8 9 do echo $var done |
- Result:
1 2 3 4 5 6 7 8 9 10 11 |
0 1 2 3 4 5 6 7 8 9 |
Until loop
- A strange sounding name loop, let’s see how it is used.
- Until loop allows to execute a script until a condition becomes true. This means that if the condition is false, then the script will be executed, and if the condition is true, then no statement will be executed. Here you can see the until loop is like a do … while loop in C ++, Java …
- Until loop always executes at least 1 time.
- Syntax:
1 2 3 4 5 |
until command do Statement(s) to be executed until command is true done |
- Example: Displays numbers from 0 to 9
1 2 3 4 5 6 7 8 |
#!/bin/bash a=0 until [ ! $a -lt 10 ] do echo $a a=`expr $a + 1` done |
Select loop
- Again a fairly new name.
- The Select loop helps create a numbered menu in order, giving the user a choice.
- Syntax:
1 2 3 4 5 |
select var in word1 word2 ... wordN do Statement(s) to be executed for every word. done |
- For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#!/bin/bash PS3='Please enter your choice: ' select DRINK in tea cofee water juice appe all none do case $DRINK in tea|cofee|water|all) echo "Go to canteen" ;; juice|appe) echo "Available at home" ;; none) break ;; *) echo "ERROR: Invalid selection" ;; esac done |
- Result:
1 2 3 4 5 6 7 8 9 10 11 |
1) tea 2) cofee 3) water 4) juice 5) appe 6) all 7) none Please enter your choice: 1 Go to canteen Please enter your choice: |
4. Functions
- Using functions to perform repetitive tasks is a great way to generate code reuse. This is an important part of modern object-oriented programming principles.
Creating Functions
1 2 3 4 |
function_name () { list of commands } |
- For example:
1 2 3 4 5 6 7 8 |
#!/bin/bash # Define your function here hello () { echo "Hello World" } # Invoke your function hello |
Pass Parameters to a Function
- We can define a function that will accept parameters while calling the function, the parameters will be denoted by $ 1, $ 2 …
1 2 3 4 5 6 7 8 |
#!/bin/bash # Define your function here hello () { echo "Hello World $1 $2" } # Invoke your function hello Zara Ali |
Returning values from Functions
- To return a value from a function we use the return statement
- Example: Returns the value 10
1 2 3 4 5 6 7 8 9 10 11 12 13 |
Live Demo #!/bin/bash # Define your function here hello () { echo "Hello World $1 $2" return 10 } # Invoke your function hello Zara Ali # Capture value returnd by last command ret=$? echo "Return value is $ret" |
Note: The function must be defined before the location to call that function.
5. Shell Substitution
- Shell performs the replacement when encountering special characters. For better understanding see the example below
1 2 3 4 |
#!/bin/bash a=10 echo -e "Value of a is $a n" |
- The -e option allows executing backslash escapes
Value of a is 10
. And this is the result without -eValue of a is 10n
. - Some escapes are used in the echo command:
- : backslash
- a : alert
- b : backspace
- c : suppress trailing newline
- f : form feed
- n : newline
- r : carriage return
- t : horizontal tab
- v : vertical tab
- You can use the -E option to disable backslash, -n to disable newline.
- Command substitution : The mechanism by which the shell executes a given script and then replaces its output where it is called.
- Syntax:
command
. Use backquote, not single quote. - Consider the following example:
1 2 3 4 5 6 7 8 |
#!/bin/bash DATE=`date` echo "Date is $DATE" USERS=`who | wc -l` echo "Logged in user are $USERS" UP=`date ; uptime` echo "Uptime is $UP" |
- Result:
1 2 3 4 5 |
Date is Thu Jul 2 03:59:57 MST 2009 Logged in user are 1 Uptime is Thu Jul 2 03:59:57 MST 2009 03:59:57 up 20 days, 14:03, 1 user, load avg: 0.13, 0.07, 0.15 |
- Variable Substitution : allows manipulating the value of a variable based on its state.
- $ {var}: Replace the value of var
- $ {var: -word}: If var is null or unset, word is substituted for var. The value of var does not change.
- $ {var: = word}: If var is null or unset, var is set to the value of word.
- $ {var:? message}: If var is null or unset, the message is printed as a standard error. This checks for variables that are set correctly.
- $ {var: + word}: If var is set, word is substituted for var. The value of var does not change.
- For example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#!/bin/bash echo ${var:-"Variable is not set"} echo "1 - Value of var is ${var}" echo ${var:="Variable is not set"} echo "2 - Value of var is ${var}" unset var echo ${var:+"This is default value"} echo "3 - Value of var is $var" var="Prefix" echo ${var:+"This is default value"} echo "4 - Value of var is $var" echo ${var:?"Print this message"} echo "5 - Value of var is ${var}" |
- Result:
1 2 3 4 5 6 7 8 9 10 11 |
Variable is not set 1 - Value of var is Variable is not set 2 - Value of var is Variable is not set 3 - Value of var is This is default value 4 - Value of var is Prefix Prefix 5 - Value of var is Prefix |
summary
- At this point, we have the basic knowledge for Shell programming, depending on each problem we will apply.
- Read more about Shell here