Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loop broken by ssh running script aside

Tags:

bash

ssh

I have a couple of machines to update some script on. I can do this with a small bash script on my side, which consists of one while loop for reading IPs from a list and calling scp for them. It works fine, but when I try to run updated script in a loop, it break the loop, although runs quite fine itself.

#!/bin/bash

cat ip_list.txt | while read i; do
    echo ${i}
    scp the_script root@${i}:/usr/sbin/ # works ok
    ssh root@${i} /usr/sbin/the_script  # works for a first IP, then breaks
done

Is this how it suppose to work? If so, how can I run a script remotely via ssh without breaking the loop?

like image 400
akalenuk Avatar asked Apr 16 '26 03:04

akalenuk


2 Answers

Use this:

ssh -n root@${i} /usr/sbin/the_script  # works for a first IP, then breaks

The -n option tells ssh not to read from stdin. Otherwise, it reads stdin and passes it through to the network connection, and this consumes the rest of the input pipe.

like image 192
Barmar Avatar answered Apr 18 '26 07:04

Barmar


You need to change the ssh line like this

ssh root@${i} /usr/sbin/the_script  < /dev/null # works for a first IP, then breaks
like image 41
Raghuram Avatar answered Apr 18 '26 07:04

Raghuram