Skip to content

Instantly share code, notes, and snippets.

@kiyoon
Created December 2, 2021 02:38
Show Gist options
  • Save kiyoon/a9f988b506234bb124ac6b200ccc5795 to your computer and use it in GitHub Desktop.
Save kiyoon/a9f988b506234bb124ac6b200ccc5795 to your computer and use it in GitHub Desktop.
Bash: save both stdout and stderr separately, whilst printing stderr.
# https://stackoverflow.com/questions/9112979/pipe-stdout-and-stderr-to-two-different-processes-in-shell-script
# Executes the command, prints the errors, and save the stdout and stderr as separate files.
save_stdouterr_print_err () {
commandstr="$1"
stdoutpath="$2"
stderrpath="$3"
if [[ $# -lt 4 ]]
then
SSH_EVAL='eval'
else
SSH_EVAL="$4"
fi
{ { { eval "$commandstr" 2>&1 1>&3; } | $SSH_EVAL "cat | tee -a '$stderrpath'"; } 3>&1 1>&2; } | $SSH_EVAL "cat >> '$stdoutpath'"
}
# Example
# Notice real-time changes. Rather than waiting until the command finishes, it actually writes on the fly.
# 1. Save locally (a.txt and b.txt)
save_stdouterr_print_err '{ echo a; sleep 5; echo >&2 b; sleep 5; echo a; sleep 5; echo >&2 b; }' a.txt b.txt
# 2. Save to ssh server (sv:~/a.txt and sv:~/b.txt)
save_stdouterr_print_err '{ echo a; sleep 5; echo >&2 b; sleep 5; echo a; sleep 5; echo >&2 b; }' a.txt b.txt 'ssh sv'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment