0

I have the command below that I used to run without $(), but I have to in order to capture the return code of the remote script. The issue is that now I don't see the command output unless I cat it. Can I see the output during execution?

set -o pipefail
COMMAND=$(ssh ${RMT_HOST} ${RMT_DIR}/${SCRIPT_NAME} ${ARGUMENTS} < /dev/null |& tee -a ${RMT_EXEC_LOG})
RETCODE=$?

EDIT Just to clear why I use $() here is a link

6
  • 4
    The usage of $() does not affect the return code... Apr 2 '18 at 15:22
  • Seconding that, you don't have to use command substitution to use $?.
    – muru
    Apr 2 '18 at 15:29
  • 2
    $? is going to contain the return code of tee, not ssh. Use ${PIPESTATUS[0]}.
    – jordanm
    Apr 2 '18 at 15:30
  • 2
    @jordanm this is way I use set -o pipefail
    – Nir
    Apr 2 '18 at 15:38
  • Your link doesn't explain why you use command substitution. If anything, the question itself makes it clear in the beginning that $? works fine without command substitution.
    – muru
    Apr 2 '18 at 15:43
1

If the question you're actually asking is "how can I both capture and display the output of a process?", you're on the right track with tee, but as others have noted, if you later look at the exit code by inspecting $?, you will be getting the exit code of tee and not of the command run through it.

It's easy to store the output and look at it later, but you need to capture the exit code immediately. Better, then, to use a temporary file and handle the output separately:

scratch="$(mktemp)"
trap 'rm -fr "$scratch"' EXIT
--SOME LONG COMMAND-- > "$scratch"
returncode=$?
--HANDLER FOR RETURNCODE--
cat "$scratch" >> /path/to/persistent_logfile

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