grep は bash スクリプトで EXIT トラップを発生させます。

grep は bash スクリプトで EXIT トラップを発生させます。

bashバージョン3.2を使用してOSXで次のスクリプトを実行する場合

#!/bin/sh

set -e
function _trap_exit {
   echo "this is a triggered trap..."
}

trap _trap_exit EXIT

/usr/sbin/ioreg -w0 -l | grep ExternalChargeCapable | grep -q No

echo "Final statement"

罠を発動させました。ただし、最終的なgrepステートメントを「yes」に変更すると、grep -q Yesトラップは実行されません。

なぜこれが起こり、どのように停止するのか知っていますか? grepの終了コードがトラップをトリガーするのはなぜですか?

ベストアンサー1

Bashのマニュアルページから...

-e      Exit immediately if a simple command (see SHELL GRAMMAR above) exits with a non-
        zero  status.   The shell does not exit if the command that fails is part of the
        command list immediately following a while or until keyword, part of the test in
        an  if  statement,  part of a && or || list, or if the command's return value is
        being inverted via !.  A trap on ERR, if  set,  is  executed  before  the  shell
        exits.

[/愚か]

時間を無駄にしてすみません...

おすすめ記事