0

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
1
  • I also changed the ssh line with the one below and it shows it's being executed, but the while still breaks: ssh 192.168.100.222 echo "1" Commented May 12, 2019 at 14:15

2 Answers 2

1

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


See: man ssh

Sign up to request clarification or add additional context in comments.

1 Comment

mystery solved! So ssh is actually eating up all the rest of stdin. Thanks for clarifying that.
1

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).

2 Comments

Thanks for that. It seems to be working well. While this fixes my immediate issue, I am still interested in understanding why iterating like in my initial solution breaks.
Because both your loop and ssh are reading from stdin and stdin is coming from <<< "${file_list}"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.