【问题标题】:Assigning variables inside remote shell script execution over SSH [duplicate]通过SSH在远程shell脚本执行中分配变量[重复]
【发布时间】:2016-11-05 04:50:07
【问题描述】:

我正在尝试通过 SSH 在远程服务器上执行一些 shell 脚本。

下面是一个代码示例:

ssh -i $KEYFILE_PATH ubuntu@$TARGET_INSTANCE_IP "bash"  << EOF
#!/bin/bash
cat /home/ubuntu/temp.txt
string=$(cat /home/ubuntu/temp.txt )
echo $string
EOF

cat 打印出预期的结果,但是 $string 不打印任何内容。

如何将cat 的返回值存储在变量中?

【问题讨论】:

    标签: linux bash shell ssh amazon-ec2


    【解决方案1】:

    您需要将 Here doc 的内容设为文字,否则它们将在当前 shell 中展开,而不是在所需的远程 shell 中。

    引用EOF

    ssh .... <<'EOF'
    ...
    ...
    EOF
    

    【讨论】:

    • 试过了!!不走运!!
    • @Silent_Rebel /home/ubuntu/temp.txt 文件在哪里?本地还是远程?
    • 它在远程服务器上..
    • 我认为这是调整..它现在正在工作..谢谢..
    【解决方案2】:

    你应该能够简单地做到这一点:

    ssh -i $KEYFILE_PATH ubuntu@$TARGET_INSTANCE_IP "bash"  <<'_END_'
        cat /home/ubuntu/temp.txt
        string=$(cat /home/ubuntu/temp.txt)
        echo $string
    _END_
    

    &lt;&lt;'_END_' ... _END_ 被称为Here Document 文字或“heredoc”文字。 '_END_' 周围的单引号可防止本地 shell 解释 heredoc 中的变量和命令。

    【讨论】:

      【解决方案3】:

      不需要中间shell(假设您在远程系统上使用bash)。 此外,您不必使用中间HERE-DOC。只需传递一个多行命令:

      ssh -i $KEYFILE_PATH ubuntu@$TARGET_INSTANCE_IP '
      
      cat /home/ubuntu/temp.txt
      string=$(cat /home/ubuntu/temp.txt )
      echo $string
      '
      

      请注意,我使用单引号来防止对本地 shell 进行评估。

      【讨论】:

        猜你喜欢
        • 2011-05-09
        • 2021-06-13
        • 2012-07-25
        • 2014-08-29
        • 2020-10-22
        • 2017-08-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多