I'm trying to create a script to ping a list of servers, and it will write the result to a text file, then it will create a folder to the list of servers.


while IFS='' read -r LINE || [[ -n "$LINE" ]]; do    
ping -c 3 $LINE >>/home/user/scripts/results.txt
sshpass -p 'P@ssword' ssh$LINE 'cd/home/user/Desktop;mkdir test'
done < "/home/user/scripts/servers.txt"

The ping is working fine, but after i add the command to create a folder, it will only have the first server ping result, and create the folder on the first server.

Any idea?

  • are you sure ssh$LINE works at all? Would ssh10.10.10.1 work from the command line (assuming a valid IP)? – jesse_b Apr 13 '19 at 13:56
  • Yes, I just tested, and works fine after add -n – EndyTerminal Apr 13 '19 at 14:06
  • 1
    @Jesse_b No, that part should never have worked unless the addresses have spaces in front of them. – Kusalananda Apr 13 '19 at 14:07
  • (1) You should always quote shell variables every time you use them unless you have a good reason not to and you’re sure you know what you’re doing.  $LINE should be "$LINE" (every time). (2) You seem to have a problem with the space bar on your keyboard.  ssh$LINE should not have worked, and cd/home/user/Desktop is definitely wrong. (3) I don’t understand what you mean by “create a  folder to the list of servers”. – G-Man Says 'Reinstate Monica' Apr 13 '19 at 14:52

ssh reads standard input. It inherits the standard input from the while loop. This means it will gobble up all the remaining lines from your file.

This is easily solved by using ssh -n which redirects /dev/null into the standard input of ssh.


while IFS= read -r addr || [ -n "$addr" ]; do    
    ping -c 3 "$addr" 
    sshpass -p 'P@ssword' ssh -n "$addr" 'mkdir Desktop/test'
done < "$HOME/scripts/servers.txt" >"$HOME/scripts/results.txt"
| improve this answer | |
  • It works!! Brilliant!!!!!!!!!! – EndyTerminal Apr 13 '19 at 14:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.