22

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 "$?" 
LOG "${RESULTS}";

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?

34

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.

local RESULTS
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
2
$ bar() { local foo=$(ls asdkjasd 2>&1); echo $?; }; bar
0
$ bar() { local foo; foo=$(ls asdkjasd 2>&1); echo $?; }; bar
2
8

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

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

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

# 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 && doExit $exit_code $err_msg

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.