The script below will break at first ssh command. Not erroring out, but breaking the while loop. Debugging the script with set -vx will indicate that the read -r line does not read anything else from the variable being iterated.

Once I comment out the ssh line, it will work happily and iterate over the entire loop.

Can you help unravel the mystery here?

Thanks!

Script:

#!/bin/bash
set -vx
file_list=$(cat <<EOT
aaa
bbbb
ccccc
dddddd
eeeeeee
EOT
)

while read -r line; do
    echo ${line}
    ssh 192.168.100.222 touch /tmp/${line}
done <<< "${file_list}"

Output with ssh line commented (set -vx was left out here)

aaa
bbbb
ccccc
dddddd
eeeeeee

Output with the ssh line enabled

aaa

2 Answers

1
Cyrus On Best Solutions

Add option -n to ssh to stop reading from stdin.


See: man ssh

1
Ed Morton On

Use an array instead of a string so you're just looping through array contents instead of relying one being able to read from stdin:

file_list=(
aaa
bbbb
ccccc
dddddd
eeeeeee
)

for file in "${file_list[@]}"; do
    echo "$file"
    ssh 192.168.100.222 touch "/tmp/$file"
done

To make it more robust google how best to populate an array from a list of newline-separated strings (look for readarray, maparray and IFS=$'\n' - I don't recall the "best" incantation off the top of my head).