Automate Network Ping Checks with Bash while/until Loops
This guide shows how to use Bash while and until loops to repeatedly run a ping command, pause between attempts, and stop automatically once the network connection succeeds, including a quick trick to repeat the previous command until it succeeds.
Repeating routine tasks such as verifying network connectivity can be automated with shell scripting. Instead of manually running ping over and over, you can wrap the command in a loop that repeats until it succeeds.
Understanding while and until loops
In Bash, a while loop executes its body while the condition is true; the loop stops when the condition becomes false. Conversely, an until loop runs its body while the condition is false and exits when the condition turns true.
1. Using a while loop
$ while ! ping -c 3 baidu.com; do sleep 2; done; echo succeedThis command repeatedly runs ping -c 3 baidu.com. The ! negates the exit status, so the loop continues while ping fails. After each failed attempt it sleeps for 2 seconds, and when ping finally succeeds the loop exits and prints succeed.
Breakdown: while ! ping -c 3 baidu.com – loop condition: continue while the ping command fails. do sleep 2; done – loop body: pause 2 seconds between attempts to avoid excessive resource usage. echo succeed – runs after the loop exits, indicating success.
2. Using an until loop
$ until ping -c 3 baidu.com; do sleep 2; done; echo succeedThe until version achieves the same result: it repeats the ping command until it returns a zero exit status, then exits the loop and prints succeed.
3. Repeating the previous command until it succeeds
You can also reuse the most recent command with !! and check its exit status via $?:
# while loop version
!!; while [ $? -ne 0 ]; do !!; done
# until loop version
until !!; do :; doneThese snippets repeatedly execute the last command ( !!) until it succeeds, using either a while loop that checks for a non‑zero status or an until loop that stops when the command succeeds.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
