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

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

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

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

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