Basic Of Shell Scripting -Part 3

Basic Of Shell Scripting -Part 3

Loops In Shell Script

A bash for loop is a bash programming language statement that allows code to be repeatedly executed. It is the repetition of a process within a bash script.
Example.
you can run the UNIX command or task 5 times or read and process a list of files using a for loop

Types Of Loops:

  1. while loop

  2. for loop

  3. until loop

  4. select loop

While Loop:

The while loop enables you to execute a set of commands repeatedly until some condition occurs. It is usually used when you need to manipulate the value of a variable repeatedly.

Syntax

while command
do
   Statement(s) to be executed if command is true
done

Example

#!/bin/sh

a=0

while [ ${a} -lt 10 ]
do
   echo ${a}
   a=`expr ${a} + 1`
done

For Loop:

The for loop operates on lists of items. It repeats a set of commands for every item in a list.

Syntax

for var in word1 word2 ... wordN
do
   Statement(s) to be executed for every word.
done

Example

#!/bin/sh
for var in Rahul Prashant Amey;
do
   echo "My Name is ${var}"
done

Until Loop:

The while loop is perfect for a situation where you need to execute a set of commands while some condition is true. Sometimes you need to execute a set of commands until a condition is true

Syntax

until command
do
   Statement(s) to be executed until command is true
done

Example

#!/bin/sh

a=0

until [ ! ${a} -lt 10 ]
do
   echo ${a}
   a=`expr ${a} + 1`
done

Select Loop:

The select loop provides an easy way to create a numbered menu from which users can select options. It is useful when you need to ask the user to choose one or more items from a list of choices.

Syntax

select var in word1 word2 ... wordN
do
   Statement(s) to be executed for every word.
done

Example

#!/bin/bash

select department in CS IT ECE EE
do
  case ${department} in

     CS)
        echo "I am from CS department."
        ;;

 IT)
        echo "I am from IT department."
     ;;

      ECE)
        echo "I am from ECE department."
     ;;

 EE)
        echo "I am from EE department."
     ;;

     none)
        break
     ;;

     *) echo "Invalid selection"
     ;;
  esac
done