出力のコピーが必要な場合は、次のtee
方法を使用できます。
#!/bin/bash
init
do_something_that_outputs_stuff_to_STDOUT | tee script.log
launch_applications_that_output_to_STDOUT | tee -a script.log
fini
ただし、これはscript.logにstdoutのみを記録します。stderrとstdoutの両方がリダイレクトされることを確認したい場合は、次を使用します。
#!/bin/bash
init
do_something_that_outputs_stuff_to_STDOUT 2>&1 | tee script.log
launch_applications_that_output_to_STDOUT 2>&1 | tee -a script.log
fini
少し機能を追加することで、少し良くすることもできます。
#!/bin/bash
LOGFILE="script.log"
# Wipe LOGFILE if you don't want to add to it at each run
rm -f "$LOGFILE"
function logcmd() {
local cmd="$1" logfile=${LOGFILE:-script.log} # Use default value if unset earlier
# Launch command, redirect stderr to stdout and append to $logfile
eval '$cmd' 2>&1 | tee -a "$logfile"
}
init
logcmd "do_something_that_outputs_stuff_to_STDOUT"
logcmd "launch_applications_that_output_to_STDOUT"
fini