问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/38135681/execute-script-over-ssh-and-get-output