Bash While Loop

27 Oct 2021 - nicolas

Also you can write directly the condition in the while statement:

i=0

while [ $i -lt 5 ]
do
    echo hello
    ((i++))
done

echo 'World! have a nice day!'

Sometime the condition can be hard to write and to read.

To avoid the hassle of writing a proper condition in my while loops, here is what I do:

yourConditionHere() {
    # your condition here
}

while true
do
    if yourConditionHere
    then
        # jump to the next iteration:
        continue
    fi

    # exit the loop:
    break
done

Example:

isIterationLowerThan5() {
    [ $i -lt 5 ]
}

i=0

while true
do
    echo hello
    ((i++))

    if isIterationLowerThan5
    then
        continue
    fi

    break
done

echo 'World! have a nice day!'

Just remember, continue will jump to the next loop iteration while break will stop and exit the loop.

Have fun!