/**/ Loops(for while until) in Shell Scripting - Dextutor

Loops(for while until) in Shell Scripting

Loops(for, while, until) in shell scripting are used to perform an operation multiple time. A loop is a portion of code that repeats (iterates) a set of commands till the loop control condition is true.

For Loop in Shell Scripting

The for loop in shell script has two syntax:

Syntax 1:

for variable in values
do
  statement1
  statement2
  ...
  statementn
done

Example 1:

Write a shell script to create files with the following names: file.txt, 123 and data.sh

for name in file.txt 123 data.sh
do
  touch $name
  echo "$name file created"
done

Example 2:

Write a shell script to create users with all the names passed at command line

for x in $*
do
 useradd $x
 echo "User created with name $x
done

Note: Creating a user requires admin privileges, so run the above script as root user

Syntax 2:

for((initialization;condition;increment/decrement))
do
  statements
done

Example 3:

Write a shell script to display the date after each second for 10 times

for((i=0;i<10;i++))
do
  date
  sleep 1;
done

Output

loops(for, while, until) in shell scripting

While Loop in Shell Scripting

The while loop tests a condition on top of the loop. The while loop keeps looping as long as the condition remains true. It is useful in conditions in which the number of loop iterations are not known beforehand.

Syntax

while [ condition ]
do
 statements
done

Example

x=0
while [ $x -le 10 ]
do
  echo "Value of x is $x"
  x=$(($x+1))
done
echo "Loop ends"

Until Loop in Shell Scripting

The until loop tests a condition on top of the loop. The while loop keeps looping as long as the condition remains false. It is useful in conditions in which the number of loop iterations are not known beforehand.

Syntax

until [ condition ]
do
 statements
done

Example

x=0
until [ $x -eq 10 ]
do
  echo "Value of x is $x"
  x=$(($x+1))
done
echo "Loop ends"

The difference between while and until loop is, in while loop the statements within the loop are executed if the condition is true wheres in until loop, the statements within the loops are executed if the condition is false.

Video Link

Practice Questions using loops(for, while, until) in Shell Scripting

Q1. Write a shell script to count the number of files having read permission within the home directory
Q2. Write a shell script to count the number of sub-directories owned by the root user within the /root directory
Q3. Write a shell script to display the owner of the file names passed at command line.

Previous
if-else


Leave a Comment