Created
December 2, 2021 02:38
-
-
Save kiyoon/a9f988b506234bb124ac6b200ccc5795 to your computer and use it in GitHub Desktop.
Bash: save both stdout and stderr separately, whilst printing stderr.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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