Bash でのエラー処理 [closed] 質問する

Bash でのエラー処理 [closed] 質問する

Bashでエラーを処理するお気に入りの方法は何ですか?私がウェブ上で見つけたエラー処理の最良の例は、William Shotts, Jrが書いたものです。http://www.linuxcommand.org

彼は、Bash でのエラー処理に次の関数を使用することを提案しています。

#!/bin/bash

# A slicker error handling routine

# I put a variable in my scripts named PROGNAME which
# holds the name of the program being run.  You can get this
# value from the first item on the command line ($0).

# Reference: This was copied from <http://www.linuxcommand.org/wss0150.php>

PROGNAME=$(basename $0)

function error_exit
{

#   ----------------------------------------------------------------
#   Function for exit due to fatal program error
#       Accepts 1 argument:
#           string containing descriptive error message
#   ---------------------------------------------------------------- 

    echo "${PROGNAME}: ${1:-"Unknown Error"}" 1>&2
    exit 1
}

# Example call of the error_exit function.  Note the inclusion
# of the LINENO environment variable.  It contains the current
# line number.

echo "Example of error with line number and message"
error_exit "$LINENO: An error has occurred."

Bash スクリプトで使用する、より優れたエラー処理ルーチンはありますか?

ベストアンサー1

罠を使おう!

tempfiles=( )
cleanup() {
  rm -f "${tempfiles[@]}"
}
trap cleanup 0

error() {
  local parent_lineno="$1"
  local message="$2"
  local code="${3:-1}"
  if [[ -n "$message" ]] ; then
    echo "Error on or near line ${parent_lineno}: ${message}; exiting with status ${code}"
  else
    echo "Error on or near line ${parent_lineno}; exiting with status ${code}"
  fi
  exit "${code}"
}
trap 'error ${LINENO}' ERR

...その後、一時ファイルを作成するたびに次の操作が行われます。

temp_foo="$(mktemp -t foobar.XXXXXX)"
tempfiles+=( "$temp_foo" )

終了時に削除され$temp_foo、現在の行番号が印刷されます。 (set -eも同様にエラー時に終了する動作をします。ただし、重大な警告が伴うコードの予測可能性と移植性が低下します。

トラップをerror自動的に呼び出すこともできます (この場合、デフォルトの終了コード 1 が使用され、メッセージは表示されません)。または、自分で呼び出して明示的な値を指定することもできます。たとえば、次のようになります。

error ${LINENO} "the foobar failed" 2

ステータス 2 で終了し、明示的なメッセージを表示します。

あるいはshopt -s extdebug、トラップの最初の行を少し変更して、ゼロ以外の終了コードをすべて全体的にトラップします (set -eエラー以外のゼロ以外の終了コードに注意してください)。

error() {
  local last_exit_status="$?"
  local parent_lineno="$1"
  local message="${2:-(no message ($last_exit_status))}"
  local code="${3:-$last_exit_status}"
  # ... continue as above
}
trap 'error ${LINENO}' ERR
shopt -s extdebug

これは とも「互換性」がありますset -eu

おすすめ記事