bash shell - ssh remote script capture output and exit code?

134,168

Solution 1

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

Solution 2

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

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

Solution 3

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
Share:
134,168

Related videos on Youtube

mconlin
Author by

mconlin

I build software and software teams.

Updated on September 18, 2022

Comments

  • mconlin
    mconlin almost 2 years

    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?

  • mconlin
    mconlin over 11 years
    you were right too, but jodanm was more faster!
  • Hauke Laging
    Hauke Laging over 11 years
    Yes, 26 seconds.
  • mmtauqir
    mmtauqir over 11 years
    Not an English class but it's incorrect to say 'more faster'.
  • mconlin
    mconlin over 11 years
    I know it was a joke. A bad one I suppose. On the internet nobody knows you are a dog.