Rajneesh Rajneesh - 1 year ago 162
Bash Question

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 [email protected]_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?

Answer Source

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 [email protected]_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 [email protected]_server remote_shell_script.sh; then
    echo 'Script executed successfully'          
else            
    echo 'Script failed'            
fi       
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download