【问题标题】:ssh command cannot return the result executed on remote machinessh 命令无法返回在远程机器上执行的结果
【发布时间】:2017-05-19 03:28:25
【问题描述】:

当我使用 ssh 在 shell 脚本中执行远程文件,以便我可以在远程机器上执行结果时,我遇到了无法识别用户定义变量的问题。

  1. 我像这样创建了一个 shell 脚本 run.sh

    #!/bin/bash
    ssh jenkins@10.122.214.55 << EOF
    ./test.sh && ret=1 || ret=0 
    echo "before" 
    echo ${ret}
    echo "after"
    echo ${HOME}
    exit ${ret}
    EOF
    
  2. run.sh 调用的 test.sh 的内容:

    #!/bin/bash
    echo "lala"
    exit 1
    
  3. 当我调用 ./run.sh 它像这样打印

    lala
    before
    
    after
    /home/jenkins
    

为什么没有回显${ret}?调用 ./run.sh 后,回显 $?是 0,这是出乎意料的,我认为它应该在这里回显 1。 谢谢!

【问题讨论】:

    标签: shell jenkins ssh


    【解决方案1】:

    因为heredoc中的变量在被发送到ssh的标准输入之前会被本地脚本扩展。

    换句话说,您的heredoc 的行为类似于

    #!/bin/bash
    string="echo \"before\"
    echo ${ret}
    echo \"after\"
    echo ${HOME}
    exit ${ret}
    ./test.sh && ret=1 || ret=0"
    echo "$string" | ssh jenkins@10.122.214.55
    

    这使得字符串插入变量更加明显。

    有几种解决方法:您可以转义$ 符号(例如echo \${ret})以便传递预期的字符串,或者您可以使用逐字的heredoc

    #!/bin/bash
    ssh jenkins@10.122.214.55 <<'EOF'
    ./test.sh && ret=1 || ret=0
    echo "before"
    echo ${ret}
    echo "after"
    echo ${HOME}
    exit ${ret}
    EOF
    

    通过单引号分隔符,我们确保在 heredoc 内不会发生扩展。

    【讨论】:

    • 非常感谢,这很有帮助
    猜你喜欢
    • 2019-11-27
    • 1970-01-01
    • 2019-05-19
    • 1970-01-01
    • 1970-01-01
    • 2012-07-27
    • 2017-02-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多