トラップ機能のエコーを再び標準出力にリダイレクト

トラップ機能のエコーを再び標準出力にリダイレクト

現在、トラップ関数の echo 文を標準出力に出力する際に​​問題があります。実行したコマンドのすべての出力(エラーおよび標準出力)をログファイルにリダイレクトします。しかし、エラーが発生した場合は、エラーをログファイルの代わりにstdoutにリダイレクトしたいと思います。

似たようなことをしようと思っていますtrap 1> on_exit EXIT。しかし、私はそれについて何も知りません。どうすればいいですか?

編集する: 説明のために、意図的にすべての出力(stderrとstdout)をログファイルにリダイレクトしました。いつでもエラーが発生した場合は、コマンドのエラー出力がログに書き込まれ(これが私が望むものです)、関数がログファイルではなくユーザービューon_exit(stdout)に出力されます。私のスクリプトには、現在のトラップ機能をログファイルに出力する機能があります。ただ標準出力に送りたいです。

#!/usr/bin/env bash
set -e

on_exit()
{
  echo "An error occurred"
}

function main()
{
  trap on_exit EXIT
  # for looping over set of commands
  $command &> "$LOGFILE"
}

main "$@"

ベストアンサー1

[これは答えではなく、意見に近いです。達成しようとする目標は明確ではありません。

これによりset -eスクリプトがエラーで終了するため、リダイレクトするには遅すぎます。

おそらくあなたは次のようなものが欲しいでしょう。

#! /bin/bash
set -o errtrace # let functions inherit the ERR trap
exec 3>&2       # save the original stderr into fd 3

on_error() {
        echo >&2 "An error occurred"    # still printed to the log the 1st time
        exec 2>&3       # switch back to the original stderr
        trap '' ERR     # disable ourselves
}
main() {
        trap on_error ERR
        no_such_command # this fail with an error
        no_such_command # again
        no_such_command # and again
}

main "$@" >/tmp/log 2>&1

実行時間:

$ bash /tmp/err
/tmp/err: line 13: no_such_command: command not found
/tmp/err: line 14: no_such_command: command not found
$ cat /tmp/log
/tmp/err: line 12: no_such_command: command not found
An error occurred

OPのスクリプトは、生のstderrにメッセージを印刷し、エラーが発生したときに終了するように修正されました。

#!/usr/bin/env bash
set -o errtrace # let functions inherit the ERR trap
exec 3>&2       # save the original stderr

on_error()
{
  echo >&3 "An error occurred"
  exit 1
}

function main()
{
  trap on_error ERR
  # for looping over set of commands
  $command &> "$LOGFILE"
}

main "$@"

実行時間:

$ command=no_such_command LOGFILE=/tmp/log bash /tmp/jeg
An error occurred
$ cat /tmp/log
/tmp/jeg: line 15: no_such_command: command not found

おすすめ記事