I wish to use shell to invoke a script on a remote server. I would like to capture the output of that script (its logging messages) and the exit code it returns.

If I do this:

ssh user@server /usr/local/scripts/test_ping.sh
echo "$?"

I get the exit code but can't capture the remote logging messages .

If I do this:

local RESULTS=$(ssh user@server /usr/local/scripts/test_ping.sh)
echo "$?" 

I get to log my output using my LOG function but can't seem to get a correct exit code, I assume the code I get is the code from the varianble assignment.

I would like to continue to use my LOG function to capture all output as it formats and sends things to a file, syslog, and the screen for me.

How can I capture results in a var AND get the correct exit code from the remote script?


3 Answers 3


The reason you are not getting the correct error code is because local is actually the last thing executed. You need to declare the variable as local prior to running the command.

RESULTS=$(ssh user@server /usr/local/scripts/test_ping.sh)
echo $?

You can see the issue here:

$ bar() { foo=$(ls asdkjasd 2>&1); echo $?; }; bar
$ bar() { local foo=$(ls asdkjasd 2>&1); echo $?; }; bar
$ bar() { local foo; foo=$(ls asdkjasd 2>&1); echo $?; }; bar

The "local" seems to be the problem. This works for me:

RESULTS=$(ssh user@server /usr/local/scripts/test_ping.sh)
echo $?
  • 2
    you were right too, but jodanm was more faster!
    – mconlin
    Mar 1, 2013 at 17:29
  • 1
    Yes, 26 seconds. Mar 1, 2013 at 17:30
  • 5
    Not an English class but it's incorrect to say 'more faster'.
    – mmtauqir
    Mar 1, 2013 at 18:34
  • 8
    I know it was a joke. A bad one I suppose. On the internet nobody knows you are a dog.
    – mconlin
    Mar 5, 2013 at 14:30
  • 1
    also jordanm's answer explains WHY this was the problem :)
    – Doktor J
    Sep 27, 2016 at 18:56

Actually, neither of the answers above traps the ssh error code and message, which could be done as follows (ignore my custom vars & funcs):

# move the deployment package from the tmp dir
msg=$(ssh -i "$(eval echo $identity_file)" -o ConnectTimeout=5 "$ssh_user"'@'"$ssh_server" \
sudo -iu "$etl_user" bash "$tgt_deployment_dir"'/src/bash/'"$run_unit/$run_unit"'.sh' \
    -a create-relative-package 2>&1)

# fail on any non-success
export exit_code=$?
export err_msg="network error: ""$msg"
test $exit_code -ne 0 && echo "$err_msg" && exit $exit_code

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .