Get the App
SLTechnology News&Howtos  ›  Servers  › 

The method of using while Loop in bash shell script

Shulou Source: shulou.com Published: 2022-06-02 01:07:14 10月03日 Update

This article is about using while loops in bash shell scripts. Xiao Bian thinks it is quite practical, so share it for everyone to make a reference. Let's follow the editor and have a look.

Like the for loop, the while loop is a loop that starts with a constraint. This means that the condition needs to be checked before executing the while loop. In most cases, it also does all the work that a for loop can do, but it has its own programming advantages.

Grammar:

while [ condition ]do//execute done

Example of while loop in bash

For example, when the value of i is greater than 10, the following loop is executed 10 times and exits.

#!/ bin/bashi=1while [$i-le10]do echo "This is looping number $i" leti++done

while infinite loop in bash

An infinite for loop is an endless loop. The loop continues until it is forced to stop using ctrl+c.

#!/ bin/bashwhiletruedo echo "Press CTRL+C to Exit"done

But we can also use conditional statements like if to terminate the loop when certain conditions are matched.

#!/ bin/bashwhiletruedo if [ condition ];do exit fidone

In bash scripts, we can also write while loops similar to C.

#!/ bin/bashi=1while((i

Tags: Loops content files conditions scripts methods more good practical endless one line that is advantages variables situations meaning articles useful see knowledge Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno NVidia Apple MySQL Shulou Technology vpn