Using until loop in Linux bash script

April 20, 2021

The until command is similar to the while command. The given statements in the loop are executed as long as they evaluate the condition as true. As soon as the condition becomes false, then the loop is exited.

The syntax is as follows:

until command 
do 
    command(s) 
done

In the following  until_01.sh script, we are printing the numbers 0-9 on screen. When the value of variable x becomes 10, then the until loop stops executing:

until_01.sh

#!/bin/bash 
x=0 
until [ $x -eq 10 ] 
do 
  echo $x 
  x=`expr $x + 1` 
done 

Let’s test the program:

$ chmod +x until_01.sh
$ ./until_01.sh

The following will be the output after executing the preceding commands:

Output:

0123456789

In the following  until_02.sh script, we ask the user to input text. We are printing text entered on the screen. When the user enters the text quit, the until loop ends the iterations:

until_02.sh

#!/bin/bash 
INPUT="" 
until [ "$INPUT" = quit ] 
do 
   echo "" 
   echo 'Enter a word (quit to exit) : ' 
   read INPUT 
   echo "You typed : $INPUT" 
done 

Let’s test the program:

$ chmod +x until_02.sh
$ ./until_02.sh

The following will be the output after executing the preceding commands:

Output:

Enter a word (quit to exit) :Ganesh
You typed : Ganesh
Enter a word (quit to exit) :Naik
You typed : Naik
Enter a word (quit to exit) :quit
You typed : quit

In the following  until_03.sh script, we are passing the username as a the command-line parameter to the script. When required, the user logs in the grep command, and they will find it from the output of the who command. Then, the until loop will stop iterations and provide information on screen about the user login:

until_03.sh

#!/bin/bash 
until who | grep "$1" > /dev/null 
do 
  sleep 60 
done 
echo -e \a 
echo "***** $1 has just logged in *****" 
exit 0 

Let’s test the program:

$ chmod +x until_03.sh
$ ./until_03.sh User10

The following will be the output after executing the preceding commands:

Output:

"***** User10 has just logged in *****"

This message will be displayed when user10 has logged in to the server.

Related Articles

Calculating and reducing the runtime of a script

In this article, we are going to learn how to calculate and reduce the script’s runtime. A simple time command will help in calculating the execution time.PrerequisitesBesides having a terminal open, make sure you have the necessary scripts present in your...

read more

Lorem ipsum dolor sit amet consectetur

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

1 − one =