Java Programming Tutorials

Java programming tutorials with many code examples!

Bash until loop

Problem:

Bash until loop is another basic construct occurring in many programming languages. It is similar to the while loop, but… different. Learn how!

Solution:

The syntax of Bash until loop is the following the same as Bash while loop, namely:

until test-commands; do consequent-commands; done

Bash until loop, in contrary to the while loop, executes as long as the status of the last of test-commands returns non-zero value. So, the test is reversed!

Se how it works in practice:

#!/bin/bash

echo "Number of params passed to the script: $#"

function param_printer() {
    # $# is number of params passed to the function!
    until [ $# -eq 0 ]; do
        echo "Parameter inside a function: ${1}"
        # shift parameters by 1 effectively dropping the first one:
        shift
    done
}

# Pass all script parameters to the function:
param_printer $@

# $# contains number of parameters
until [ $# -eq 0 ]; do
    # print the first parameter
    echo "Parameter: ${1}"
    # shift parameters by 1 effectively dropping the first one:
    shift
done

As you can see the loop executes as long as the condition is false.

Running the script gives the following output:

$> ./until-loop.sh a b c
Number of params passed to the script: 3
Parameter inside a function: a
Parameter inside a function: b
Parameter inside a function: c
Parameter: a
Parameter: b
Parameter: c

It’s clear that the Bash while loop and Bash until loop are like two sides of the same coning – one is negation of another.

Share with the World!