Why Your SSH Loop Stops After One Host—and How to Fix It
Learn why a Bash script that reads IPs from a file and uses SSH in a while loop only processes the first host, and discover two reliable solutions—switching to a for loop or adding the -n option to SSH—to ensure all servers are queried correctly.
Scenario
You want a script that reads a list of server IPs from ip.txt (one IP per line) and, using a pre‑configured SSH key, fetches each server's uptime without prompting for a password.
Initial script (while loop)
#!/bin/bash
while read ips; do
echo $ips;
upt=`ssh root@$ips "uptime"`;
echo $upt;
done < ip.txtThis script reads the IPs correctly, but it only processes the first IP and then exits.
Problem Analysis
The while loop reads ip.txt via input redirection. When the ssh command runs inside the loop, it also reads from standard input, consuming the remaining lines of ip.txt. As a result, the loop thinks there is no more input and terminates after the first iteration.
Solution Strategies
1. Use a for loop
A for loop iterates over the list without pre‑loading the entire file, avoiding the stdin conflict.
#!/bin/bash
for ips in `cat ip.txt`; do
echo ${ips};
upt=`ssh root@${ips} uptime`;
echo $upt;
done2. Keep the while loop but add -n to ssh
The -n option redirects ssh 's standard input from /dev/null, preventing it from consuming the remaining IPs.
#!/bin/bash
while read ips; do
echo $ips;
upt=`ssh -n root@$ips "uptime"`;
echo $upt;
done < ip.txtBoth approaches ensure that the script processes every IP address in the list.
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.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
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.
