简体   繁体   English

如何将状态代码从远程运行的Shell脚本返回到本地Shell脚本

[英]How to return a status code from a remotely run shell script to a local shell script

I am running a remote shell script from a local shell script using ssh. 我正在使用ssh从本地Shell脚本运行远程Shell脚本。 Below is the code in my local shell script: 以下是我的本地shell脚本中的代码:

ssh userid@remote_server '/bin/bash' << EOF
    if remote_shell_script.sh ; then
           echo 'Script executed successfully'
    else
        echo 'Script failed'
    fi
EOF

The above script is working fine. 上面的脚本工作正常。 But I am not able to return a status code to a local shell script that I can use locally. 但是我无法将状态代码返回到可以在本地使用的本地Shell脚本。 I want to return a status code (0,1) inside the EOF..EOF here statements that I can capture in my local script and then take action accordingly. 我想在EOF..EOF here语句中返回状态代码(0,1),可以在本地脚本中捕获该语句,然后采取相应措施。 How can I do this? 我怎样才能做到这一点?

The exit code of the EOF block will be passed back to the outer shell. EOF块的退出代码将传递回外壳。 The issue you may have is that the exit code of remote_shell_script.sh is being swallowed. 您可能遇到的问题是, remote_shell_script.sh的退出代码被吞咽了。 You can fix that a couple of ways. 您可以通过以下两种方法来解决。 One is to exit with an appropriate exit code. 一种是exit与适当的退出代码。

ssh userid@remote_server '/bin/bash' << EOF
    if remote_shell_script.sh ; then
        echo 'Script executed successfully'
        exit 0
    else            
        echo 'Script failed'
        exit 1
    fi       
EOF

echo "Exit code = $?"

A simpler way is to move the checking logic to the local server. 一种更简单的方法是将检查逻辑移动到本地服务器。 In that case you don't even need the EOF here document. 在这种情况下,您甚至都不需要EOF这里的文档。

if ssh userid@remote_server remote_shell_script.sh; then
    echo 'Script executed successfully'          
else            
    echo 'Script failed'            
fi       

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM