1

Any one knows why ssh command leading to unexpected exit in bash while loop?

this is a simplified demo script which intends to read 3 lines of folder name in $folder variable and ls each one in a remote machine by ssh.

#!/bin/bash
folders="a
b
c"

echo "$folders" | while read d
do
        echo "ls ==$d=="
        # ssh tony@remote_machine "ls -l /tmp/$d"
done
echo DONE

if I commented out the ssh remote command execution in while loop, i can make sure that there execute totally 3 loops in while.

ls ==a==
ls ==b==
ls ==c==
DONE

However, if I enable ssh remote command execution in while loop, the strange thing is that only 1 time in while loop executes and then the while loop exits unexpectedly like below:

ls ==a==
total 24
... <omitted by Tony>
DONE

I know I can use for d in $folders; do ssh ... done. But i want to know where I am wrong with the style 'echo $xxx | while read line'. Why ssh will result in unexpected exits in while loop?

Thanks

Cyrus
  • 84,225
  • 14
  • 89
  • 153
Tony Su
  • 57
  • 6
  • Thanks @Cyrus. My question has been answered and solved correctly. sorry for the duplication as I failed to search the correct keywords. – Tony Su Sep 21 '18 at 03:23

0 Answers0