Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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 cant 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 cant 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?

share|improve this question
add comment

2 Answers

up vote 6 down vote accepted

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
share|improve this answer
add comment

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

local RESULTS
RESULTS=$(ssh user@server /usr/local/scripts/test_ping.sh)
echo $?
share|improve this answer
    
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
    
Not an English class but it's incorrect to say 'more faster'. –  mtahmed Mar 1 '13 at 18:34
    
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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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