0

I need to make my script iterate through a list of servers, but I can't.
Suppose that 192.168.0.1 and 192.168.0.2 are listed in the file that will be read by the script, when executing it only the first line (192.168.0.1) is successfully processed and nothing happens with the second line (192.168.0.2).

This is the script:

#!/bin/bash

# Read in server names from afile
while read -r server; do
# Check if server is reachable
if ping -c 1 "$server" &> /dev/nul l; then 
    echo "Server $server is reachable."
    # Check if mount point exists
    if ssh "$server" "[ -d /path/to/mount/point ]"; then
        echo "Mount point exists on server $server."
    else
        echo "Mount point does not exist on server $server."
    fi
else
    echo "Server $server is not reachable."
fi
done < servers.txt

How to go through the entire list of servers successfully?

indra
  • 19
  • 6
  • 4
    `ssh` will read the rest of the servers.txt file during the first iteration, preventing the `while read` part from seeing it. See ["Bash While loop read file by line exit on certain line"](https://stackoverflow.com/questions/65709042/bash-while-loop-read-file-by-line-exit-on-certain-line) and [BashFAQ #89: "I'm reading a file line by line and running ssh or ffmpeg, only the first line gets processed!"](http://mywiki.wooledge.org/BashFAQ/089) – Gordon Davisson Feb 15 '23 at 09:28
  • 1
    Yes, you can use FD 3 , but I still find `echo hoppa | ssh "$server" "[ -d /path/to/mount/point ]"` the easiest solution to explain. – Ljm Dullaart Feb 15 '23 at 10:27
  • Where should I need to make the changes – indra Feb 15 '23 at 11:03
  • Thankyou all for your spontaneous replies. It worked – indra Feb 17 '23 at 18:50

1 Answers1

3

As pointed out in the comments section, ssh command is consuming your script stdin.

Add -n option to ssh should prevent this (see this).

So change this line:

if ssh "$server" "[ -d /path/to/mount/point ]"; then

To:

if ssh -n "$server" "[ -d /path/to/mount/point ]"; then
Jardel Lucca
  • 1,115
  • 3
  • 10
  • 19