ablog

不器用で落着きのない技術者のメモ

シェルスクリプトのエラー処理を見やすく書く

bashシェルスクリプトを書いていて、エラー処理をif文を使って

command ...
if [ $? -ne 0 ]
then
        echo ...
        exit 1
fi

みたいに書くと、コードが見づらいのでなんとかならないかと思っていたら、

command ... || { echo ... ; exit 1 ; }

こういう風に書けるのか。
Perl の「or die」みたい。ってか Perl のほうが新しいと思うけど。

command ... || echo ... ; exit 1

のように書くと exit が実行されないので要注意。って bashクックブック に書かれてました。

  • hoge1.sh
#!/bin/bash

mkdir log
if [ $? -ne 0 ]
then
        echo oops!
        exit 1
fi

echo created directory.
  • hoge2.sh
#!/bin/bash

mkdir log || { echo oops!; exit 1; }

echo created directory.
  • 実行結果
$ touch log
$ ./hoge1.sh          
mkdir: cannot create directory `log': File exists
oops!
$ ./hoge2.sh 
mkdir: cannot create directory `log': File exists
oops!

参考

bashクックブック

bashクックブック

P.85-86 レシピ4.8 失敗時のエラーメッセージの表示