Skip to content

Instantly share code, notes, and snippets.

@pmarreck
Created October 25, 2021 22:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pmarreck/5eacc6482bc19b55b7c2f48b4f1db4e8 to your computer and use it in GitHub Desktop.
Save pmarreck/5eacc6482bc19b55b7c2f48b4f1db4e8 to your computer and use it in GitHub Desktop.
A bash function to capture the stdout, stderr and return code of any line of shell into separate name-provided variables all at once without using the filesystem
capture () {
local out_var out err_var err ret_var ret debugflag
debugflag=
if [ "$1" = "--debug" ]; then
debugflag=1
shift
fi
if [ "$#" -lt 4 ]; then
echo "Usage: capture [--debug] <stdoutvar> <stderrvar> <returncodevar> command [arg ...]"
return 1
fi
out_var="$1"; shift
err_var="$1"; shift
ret_var="$1"; shift
# just some nutso magic that captures stdout into $out, stderr into $err and return/status code into $ret
# WITHOUT opening files, because touching the filesystem unnecessarily is bad (slows down tests, etc)
. <({ err=$({ out=$("$@"); ret=$?; } 2>&1; declare -p out ret >&2); declare -p err; } 2>&1)
if [ $debugflag ]; then
echo "Command run:"
echo "$@"
echo "stdout:"
echo $out
echo "stderr:"
echo $err
echo "return/exit code:"
echo $ret
fi
read $out_var <<<$out
read $err_var <<<$err
read $ret_var <<<$ret
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment