A junior administrator created the following health-check script:
#!/usr/bin/env bash
while nc -z localhost 443; do # line 2
echo "Waiting for HTTPS service…"
sleep 10
done
echo "Service is ready."
The intention is to keep retrying every 10 seconds while the port is closed and exit the loop as soon as the port becomes reachable. In practice, the script does the opposite-it loops when the service is already up and stops when the service is down.
Without replacing the while keyword with until, which single change on line 2 correctly fulfills the requirement?
until nc -z localhost 443; do
while nc -z localhost 443 || sleep 10; do
while ! nc -z localhost 443; do
while nc -z localhost 443 >/dev/null 2>&1; [ $? -ne 0 ]; do
In Bash, the body of a while loop runs as long as the controlling command returns an exit status of 0 (success). The nc -z test returns 0 when the TCP port is open and 1 when it is closed. Because the original script runs the loop while the test succeeds, it prints the message only when the service is already available.
Negating the test with a leading ! inverts the exit status: the loop now continues while the port is closed (non-zero from nc) and terminates immediately after the first successful probe (exit status 0), allowing the script to proceed. The other options either keep the original (wrong) logic, misuse exit-status handling, or switch to an until loop contrary to the stated constraint.
Ask Bash
Bash is our AI bot, trained to help you pass your exam. AI Generated Content may display inaccurate information, always double-check anything important.
What is the purpose of the 'nc -z' command in the script?
Open an interactive chat with Bash
Why does adding '!' to the condition correct the script behavior?
Open an interactive chat with Bash
What does the '>/dev/null 2>&1' syntax achieve, and why wasn’t it needed here?
Open an interactive chat with Bash
CompTIA Linux+ XK0-006 (V8)
Automation, Orchestration, and Scripting
Your Score:
Report Issue
Bash, the Crucial Exams Chat Bot
AI Bot
Loading...
Loading...
Loading...
IT & Cybersecurity Package Join Premium for Full Access