0

I want to log the output of a script; hence, I pipe from the block containing most of my code to tee. However, I have trouble with variables' values being lost when the pipeline exits. For example:

{
  (exit 3) # do something
  result=$?
} 2>&1 | tee -ia /var/log/action.log

exit "$result" # this needs to also exit with status 3

How do I return the value set inside the piped code block?

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
crackpot
  • 333
  • 1
  • 2
  • 16

1 Answers1

1

The problem isn't the curly braces, it's the pipeline. Replace it with a process substitution, and the issue goes away. In bash (as the question was initially tagged for):

#!/usr/bin/env bash
#              ^^^^- NOT sh
{
  # do something
  result=$?
} > >(tee -ia /var/log/action.log) 2>&1

exit "$result"

Whereas with POSIX sh, you might end up with something more like:

#!/bin/sh
tempdir=$(mktemp -d "${TMPDIR:-/tmp}/myprogram.XXXXXX") || exit
mkfifo "$tempdir/fifo" || exit
tee -ia /var/log/action.log <"$tempdir/fifo" &

{
  rm -rf -- "$tempdir" # no longer needed after redirections are done
  # ...other code here...
  result=$?
} >"$tempdir/fifo" 2>&1

exit "$result"
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441