2. Shell script loop & conditional statement

Like other programming languages, shell script also have same loop concept, let us look at different types of loop syntax how it will work in shell scripts.

For loop

for x in hi 1 * 2 A bye 
  echo "display ... x is set to $x"
display ... i is set to hi
display ... i is set to 1
display ... i is set to index.php
 //* -> Print current directory fies
display ... i is set to index.sh
display ... i is set to 2
display ... i is set to A
display ... i is set to bye

While Loops

: always define as true, test below example. read is the command take user input, we will learn it later in details.

while :
  echo "Type something in (^C to quit)"
  echo "You have typed : $READ_STRING"

What ever you typed it will display but never exit until you press ctrl + C 
while [ "$INPUT_VAL" != "bye" ]
  echo "Type something in (bye to quit)"
  read INPUT_VAL
  echo "You typed: $INPUT_VAL"
Promt will ask again and again until you type "bye".

Creating Directory

mkdir index_{1,2,3} // it will create 3 directory index_1, index_2 and index_3
------------------- Same can be done with for loop------------------
for key in 1 2 3
  mkdir index_${key}
//The output will be the same
mkdiir -p {,usr,usr/local}/{bin,sbin,lib}

Conditional Statements

if <SPACE> [ <SPACE> "$x" <SPACE> = <SPACE> "string" <SPACE> ] This space are very much required while writing conditional statement in shell script.

#! /bin/bash

echo "Enter something"
read price
if [ $price -eq 0 ]; then
  echo "Zero"
  elif [ $price -gt 0 ]; then
    echo "above Zero"
  elif [ $price -lt 0 ]; then
    echo "Less than zero"
    echo "None"

Few Short hand syntactic sugar things are as follows

#! /bin/bash
echo "Enter something"
read price
[ $price -gt 0 ] && echo "Greater Than zero" || echo "Less Than zero"
[ -n $price ] && echo "Price is of non-zero length" || echo "price is of zero length"

We can check a list of conditional operators for the comparison in shell script.

#! /bin/bash

echo "Enter something"
read price
echo $price | grep [^0-9] > /dev/null 2>&1
#echo $? Prints 0 For string and 1 for numerical value
if [ $? -eq 0 ]; then
  echo "Required Numerical value"
  echo "It\"s a numerical value"
  • The >/dev/null 2>&1 directs any output or errors to the special “null” device, instead of going to the user’s screen.
  • $? exit status of last command
  • grep [0-9] finds lines of text which contain digits (0-9) and possibly other characters.

Switch Case

#! /bin/bash

while :
  echo "Enter the price"
  read price
  case $price in
    7) echo "Exact price" 
    8) echo "Slightly Infleted";;
 #Integer Value
    "Do not know") echo "Please try ti find the value";;
 #String Value
    *) echo "Default case";;
 #Default Value
  • while : always true
  • break;; exiting from the loop, other wise promt will ask repeatedly
  • * Is a default value case
  • "value") case statement