简体   繁体   中英

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. Below is the code in my local shell script:

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. 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. How can I do this?

The exit code of the EOF block will be passed back to the outer shell. The issue you may have is that the exit code of remote_shell_script.sh is being swallowed. You can fix that a couple of ways. One is to exit with an appropriate exit code.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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