Skip to content

Instantly share code, notes, and snippets.

@zmwangx
Created July 15, 2015 16:20
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zmwangx/efababea6258cedea07a to your computer and use it in GitHub Desktop.
Save zmwangx/efababea6258cedea07a to your computer and use it in GitHub Desktop.
Zsh save stdout, stderr, and return value to different variables without temp file. The following construct evaluates "$@" and saves output on stdout in the parameter stdout, output on stderr in the parameter stderr, and return value in the parameter return. The idea was based on http://stackoverflow.com/a/18086548/1944784, but this implementati…
# The following construct evaluates "$@" and saves output on stdout in the
# parameter stdout, output on stderr in the parameter stderr, and return value
# in the parameter return.
#
# The idea was based on http://stackoverflow.com/a/18086548/1944784, but this
# implementation is completely race-condition-free. The implementation was
# refined during my exchange with Mathias Fredriksson @mafredri, in
# https://github.com/mafredri/zsh-async/issues/1. See mainly
# https://github.com/mafredri/zsh-async/issues/1#issuecomment-121468958, where
# the advantage of this implementation is explained.
unset stdout stderr ret
eval "
$(
{
stdout=$(eval "$@")
ret=$?
typeset -p stdout ret
} 2> >(stderr=$(cat); typeset -p stderr)
)"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment