次の要件に従って、echoでteeコマンドを使用する方法は?

次の要件に従って、echoでteeコマンドを使用する方法は?

コマンドとログファイル名を含む変数を追加すると、変数の内容が印刷されるteeため、期待した結果は得られません。echo

以下は、ファイルの内容、実際の出力、予想される結果です。

シェルスクリプトの内容:

#!/bin/bash

log="2>&1 | tee -a report.txt"

echo ""
echo '***************-:START OF THE REPORT:-***********' $log

スクリプトを実行した後。

console op:
***************-:START OF THE REPORT:-*********** 2>&1 | tee -a report.txt

予想される -

console op:
***************-:START OF THE REPORT:-***********

report.txt file content:
***************-:START OF THE REPORT:-***********

また、各echoコマンドの最後にコマンドをハードコードしたくないので、変数にはコマンドとファイル名を$log含める必要があります。teetee

ベストアンサー1

teeそれぞれにタグを付けたくないので、実際のパイプにタグを付け、ログメッセージの最後にタグを付けるこの珍しい方法を使用したいとしますecho

さて、次のようにすることもできます。

logfile='report.txt'

log () {
    if [ -z "$1" ]; then
        cat
    else
        printf '%s\n' "$@" 
    fi | tee -a "$logfile"
}

log "some message"
log "some other message"
log "multi" "line" "output"

{
    cat <<LETTER
Dear Sir,

It has come to my attention, that a whole slew of things may be
collected and sent to the same destination, just by using a single
pipe. Just use { ... } | destination

Sincerely, $LOGNAME
LETTER

    cat <<THE_PS
PS.
Here's the output of "ls -l":
THE_PS

    ls -l

    echo "LOL"

} | log

つまり、扱いにくいteeコマンドを入力しやすい名前の単純なシェル関数で包み、出力をパイプで連結するだけです。

この例では、関数はコマンドラインに提供されたデータを出力したり、コマンドライン引数でない場合に標準入力から読み取りに切り替えるためにlog使用されます。printf

使用することもできます

./your_original_script_without_special_logging 2>&1 | log

おすすめ記事