日付と時刻のロギングのためのstderr stdoutもttyに出力を表示しますが、日付と時刻は表示しません。

日付と時刻のロギングのためのstderr stdoutもttyに出力を表示しますが、日付と時刻は表示しません。

関数内でいくつかのコマンドを実行しています。日付と時刻を追加して、この関数の各コマンド出力を記録したいと思います。ところで、実行時にターミナルでは日付や時間なしでメインの一般出力のみを表示したいと思います。

それでは、このような関数を使ってexec 3>&1 1>>${log} 2>&1これらすべてをどのようにパイプしますか?adddate

./script | adddate >>$logこれにより、date各行のログ出力を取得できますが、同時に端末に出力を表示することもできます。

私はttyに日付と時刻を表示したくないだけでログに保存したいと思います。ユーザーがいつでも渡すことができる誤った引数などをキャプチャし、同時にttyでスクリプトを実行しているユーザーに出力を表示したいので、これを行っています。

これまで私は次のことをしました。

#!/usr/bin/env bash
log=logs.txt
exec 3>&1 1>>${log} 2>&1 ## works but without date

それから以下のようなことを試しました。正しく行う方法がわかりません。

3>$1 1>> | adddate ${log} 2>&1 ###(!) doesnt work
exec 3>&1 | adddate 1>> ${log} 2>&1 ###(!) doesnt work

adddatemain機能は次のとおりです。

adddate() {
    while IFS= read -r line; do
        printf "%s %s\n" "$(date)" "$line";
    done
}

main()
{

case $arg in
        --version)
                [[ "$arg2" == "" ]] && { --version; } || { error; } ;;

        build)
                [[ "$arg2" == "oneshot"  ]] && {
                        build oneshot; } || {
                        build;
                         } ;;
        update)
                [[ "$arg2" == "" ]] && { update; } || { error; } ;;
        *)
                error
esac

}

arg=$1;
arg2=$2;
shift;

main | tee /dev/fd/3; ## so that it goes to tty, not sure if there is other better way?!?

mainつまり、ログは次のようになります。各コマンドについて、関数に似たコマンドを出力する前に、日付と時刻をログに記録する必要があります。

main()
{
   printf "Hello\n";
   printf "there!\n";
}

ログアウトは次のようになります。

Mon Jun 17 20:00:02 JST 2019 Hello
Mon Jun 17 20:00:02 JST 2019 there!

ttyはログを表示せず、デフォルトの出力のみを表示する必要があります。たとえば、次のようになります。

Hello
there!

ベストアンサー1

誰かがこれを改善できることを願っています。

私は最初にこのようなコマンドを使用しますtsmoreutils

#!/usr/bin/env bash

command -v ts > /dev/null 2>&1 [[ $? -ne 0 ]] && { sudo apt install moreutils -y; };

log="./testlog.txt"
comm()
{
        printf "Hi\n";
        echo "here is a wrong command"
        csdf;
        echo "bye"
}

exec 3>&1 1>>${log} 2>&1;
comm | tee /dev/fd/3 | ts;

そしてそうではありませんts

#!/usr/bin/env bash

log="./testlog.txt"
comm()
{
        printf "Hi\n";
        echo "here is a wrong command"
        csdf;
        echo "bye"
}
dddate() 
{
while IFS= read -r line; do
        printf '%s %s\n' "$(date)" "$line"
done
}

exec 3>&1 1>>${log} 2>&1;
comm | tee /dev/fd/3 | dddate;

ログファイルから:

./test.sh: line 10: csdf: command not found
Mon Jul  8 12:23:44 UTC 2019 Hi,
Mon Jul  8 12:23:44 UTC 2019 here is a wrong command
Mon Jul  8 12:23:44 UTC 2019 thanks

ターミナルから:

Hi,
here is a wrong command
thanks

おすすめ記事