Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

bash

shell

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?

like image 890
Rajneesh Avatar asked Oct 19 '25 14:10

Rajneesh


1 Answers

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       
like image 126
John Kugelman Avatar answered Oct 21 '25 04:10

John Kugelman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!