Detailed until loop Bash in

Cycling is one of the basic concepts of programming languages. When you want to run a series of commands over and over again until it reaches a termination and exit conditions, circulation is very convenient.

Such as scripting languages like Bash, the cycle is useful to automate repetitive tasks. In Bash script has three basic cyclic structure, for loop , the while loop , an until loop .

This tutorial explains the basics until loop Bash in.

Bash until the cycle

until loop is used when a calculation result given condition is false, execution is repeated a given set of commands.

Bash until cycle takes the following form:

until [CONDITION]
do
  [COMMANDS]
done

Calculation conditions before executing the command. If the condition evaluates to false, the command is executed. Otherwise, if the condition evaluates to true, then the loop will terminate, program control passes to the subsequent commands.

In the following example, at each iteration, the current value of the loop variable print counter is incremented by one and variable.

#!/bin/bash

counter=0

until [ $counter -gt 5 ]
do
  echo Counter: $counter
  ((counter++))
done

As long as the value of the counter variable is greater than 5, the loop iteration terminates. The script produces the following output:

Counter: 0
Counter: 1
Counter: 2
Counter: 3
Counter: 4
Counter: 5

Bash until exemplary cycle

If your git downtime will host the following script can be very useful, you can run the script once, instead of manually typing git pull you many times, until the host is online. It will try to pull out the store, pulled out until it succeeds.

#!/bin/bash

until git pull &> /dev/null
do
    echo "Waiting for the git host ..."
    sleep 1
done

echo -e "\nThe git repository is pulled."

The script will print "Waiting for the git host ..." and sleep for one second until the git main line. Once the repository is pulled out, it will print "git repository is pulled.."

Waiting for the git host ...
Waiting for the git host ...
Waiting for the git host ...

The git repository is pulled.

in conclusion

while and until the cycle is very similar, as long as the while loop iteration, as long as the condition evaluates to, true and until loop iteration, as long as the condition evaluates to false.

Guess you like

Origin www.linuxidc.com/Linux/2019-08/159854.htm