安全のために構文エラーが発生した場合は、bashにスクリプトの実行を中止させたいと思います。
驚いたことに、私はこれを達成できませんでした。 (set -e
不足しています。 )例:
#!/bin/bash
# Do exit on any error:
set -e
readonly a=(1 2)
# A syntax error is here:
if (( "${a[#]}" == 2 )); then
echo ok
else
echo not ok
fi
echo status $?
echo 'Bad: has not aborted execution on syntax error!'
結果(bash-3.2.39またはbash-3.2.51):
$ ./sh-on-syntax-err
./sh-on-syntax-err: line 10: #: syntax error: operand expected (error token is "#")
status 1
Bad: has not aborted execution on syntax error!
$
$?
まあ、構文エラーを見つけるためにすべての文を確認することはできません。
(私は合理的なプログラミング言語でこれらの安全な動作を期待しています...おそらくこれはbash開発者にバグ/要望として報告されるべきです)
その他の実験
if
他に何もない。
削除if
:
#!/bin/bash
set -e # exit on any error
readonly a=(1 2)
# A syntax error is here:
(( "${a[#]}" == 2 ))
echo status $?
echo 'Bad: has not aborted execution on syntax error!'
結果:
$ ./sh-on-syntax-err
./sh-on-syntax-err: line 6: #: syntax error: operand expected (error token is "#")
status 1
Bad: has not aborted execution on syntax error!
$
おそらくエクササイズ2と関係があるようです。http://mywiki.wooledge.org/BashFAQ/105と関連付けられる(( ))
。しかし、構文エラーが見つかった後でも実行を続けることはまだ意味がありません。
いいえ、(( ))
違いはありません!
算術テストなしでパフォーマンスが良くなかった!簡単な基本スクリプト:
#!/bin/bash
set -e # exit on any error
readonly a=(1 2)
# A syntax error is here:
echo "${a[#]}"
echo status $?
echo 'Bad: has not aborted execution on syntax error!'
結果:
$ ./sh-on-syntax-err
./sh-on-syntax-err: line 6: #: syntax error: operand expected (error token is "#")
status 1
Bad: has not aborted execution on syntax error!
$
ベストアンサー1
すべてを関数で包むことはトリックを実行するようです。
#!/bin/bash -e
main () {
readonly a=(1 2)
# A syntax error is here:
if (( "${a[#]}" == 2 )); then
echo ok
else
echo not ok
fi
echo status $?
echo 'Bad: has not aborted execution on syntax error!'
}
main "$@"
結果:
$ ./sh-on-syntax-err
$ ./sh-on-syntax-err line 6: #: syntax error: operand expected (error token is "#")
$
理由はわかりませんが、他の人が説明できますか?