Operations 4 min read

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.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Why Your SSH Loop Stops After One Host—and How to Fix It

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.txt

This 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;
done

2. 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.txt

Both approaches ensure that the script processes every IP address in the list.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

automationBashSSHscript/loop
MaGe Linux Operations
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.