次のような expr_sample0.sh があったとします。
expr "$1" + 1 > /dev/null if [ $? -le 1 ]; then echo "$1 is number" else echo "$1 is not number" fi
コマンドを実行するときにパラメータへ数字を渡すときはいいのですが、文字を渡してエラーとするときに、exprコマンドのエラーも一緒に表示されてしまいます。
$ sh expr_sample0.sh 1 1 is number $ sh expr_sample0.sh 2 2 is number $ sh expr_sample0.sh a expr: not a decimal number: 'a' a is not number
コマンドを実行した時に、コンソール画面へエラーが表示されると困るときもあるので、スクリプトで使っているコマンドでエラーが発生した場合は何も出力しないようにしたいときがあります。
そんなときは、「コマンド > /dev/null 2>& 1」とします。ここの2はエラー出力用のスペシャルデバイスファイルで、1は標準出力用のスペシャルデバイスファイルを表しています。expr_sample0.sh へ適用してみましょう。
$ cat expr_sample.sh expr "$1" + 1 > /dev/null 2>& 1 if [ $? -le 1 ]; then echo "$1 is number" else echo "$1 is not number" fi
実行結果は次のようになり、exprコマンドの実行結果が表示されなくなったことがわかります。
$ sh expr_sample.sh 2 2 is number $ sh expr_sample.sh 3 3 is number $ sh expr_sample.sh a a is not number