Skip to content

Click on each book below to review & buy on Amazon.

As an Amazon Associate, I earn from qualifying purchases.


CompTIA Linux+ XK0-005 - 3.1 - Shell Script Elements: until Loops

In shell scripting, an until loop allows you to repeatedly execute a block of code until a specific condition becomes true. It is similar to a while loop but with a reversed logic. The code block inside the loop will execute as long as the condition is false. Once the condition becomes true, the loop terminates, and the script continues with the subsequent commands.

Basic Syntax

The basic syntax of an until loop in shell scripting is as follows:

until condition
do
    # Code to be executed until the condition is true
done
  • condition is an expression or command that evaluates to either true or false. The code block within the loop will execute until the condition becomes true.

Example: Printing Numbers in Reverse Order

#!/bin/bash

counter=10

until [ $counter -lt 1 ]
do
    echo "Counter: $counter"
    ((counter--))
done

In this example, the until loop is used to print numbers in reverse order starting from 10. The condition [ $counter -lt 1 ] checks if the value of the counter variable is less than 1. As long as the condition is false, the loop continues to execute, decrementing the counter variable and printing its value. Once the counter variable becomes less than 1, the condition becomes true, and the loop terminates.

Example: Reading User Input

#!/bin/bash

input=""

until [ "$input" == "quit" ]
do
    echo "Enter a value (type 'quit' to exit): "
    read input
    echo "You entered: $input"
done

In this example, the until loop is used to repeatedly ask the user for input until they enter the word "quit". The condition [ "$input" == "quit" ] checks if the value of the input variable is equal to "quit". As long as the condition is false, the loop prompts the user for input, reads the input, and displays it. Once the user enters "quit", the condition becomes true, and the loop terminates.

Conclusion

Until loops are useful constructs in shell scripting that allow you to repeatedly execute a block of code until a specific condition becomes true. By understanding the basic syntax and examples provided, you can effectively use until loops to automate tasks and control the flow of your shell scripts.

Remember to customize the condition and the code block within the loop to suit your specific requirements. The condition should evaluate to either true or false, and the code block should contain the necessary commands or operations to be executed until the condition becomes true.


Support DTV Linux

Click on each book below to review & buy on Amazon. As an Amazon Associate, I earn from qualifying purchases.

NordVPN ®: Elevate your online privacy and security. Grab our Special Offer to safeguard your data on public Wi-Fi and secure your devices. I may earn a commission on purchases made through this link.