5

I am trying to execute a command in a remote machine and get the output.

I have tried implementing below shell script but unable to get the content.

#!/bin/bash

out=$(ssh huser@$source << EOF
while IFS= read -r line
do
echo 'Data : ' $line
done < "data.txt"
EOF
)

echo $out

Output:

Data : Data : Data : 

I could see the "Data :" is printed 3 times because the file "data.txt" has 3 lines of text.

I can't use scp command to get the file directly because I might have to run some command in the place of text file.

Can someone help me in finding the issue?

Thanks in advance.

4
  • 1
    If you put four spaces at the start of each line of your code, instead of ">", it will format better. Or remove the >s and hit the {} button. Commented Jul 1, 2016 at 1:29
  • BTW, shellcheck.net is your friend. Commented Jul 1, 2016 at 1:31
  • ...big chunks of this are duplicative of stackoverflow.com/questions/2374276/… -- the rest is just the quoting on the expansion on the echo. Commented Jul 1, 2016 at 1:34
  • Thank you all for the suggestions. Commented Jul 1, 2016 at 17:53

1 Answer 1

5

The problem doesn't have anything to do with ssh at all:

echo $out

is mangling your data. Use quotes!

echo "$out"

Similarly, you need to quote your heredoc:

out=$(ssh huser@$source <<'EOF'
  while IFS= read -r line; do
    printf 'Data : %s\n' "$line"
  done < "data.txt"
EOF
)

Using <<'EOF' instead of <<EOF prevents $line from being expanded locally, before the code has been sent over SSH; this local expansion was replacing echo 'Data : ' $line with echo 'Data : ', because on your local system the line variable is unset.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.