Execute script over SSH and get output? [duplicate]

 ̄綄美尐妖づ 提交于 2020-01-15 07:42:06

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!