シェルスクリプトの if
では条件が真の場合になにも処理を書いていない場合、エラーとなります。
if [ 条件式 ] ; then
#なにもしない(あとで実装予定)
else
if [ 条件式 ] ; then
exit 0
else
exit 1
fi
fi
echo 'successful'
なので、↑このスクリプトを実行するとエラーになります。
$ bash if_sample.sh
if_sample.sh: line 3: syntax error near unexpected token `else'
if_sample.sh: line 3: `else'
開発途中で真の場合の実装を後回しにする場合にこれだと都合が悪いので、シェルスクリプトの if
で条件式が真のときに「なにもせず後続の処理を続けたい」という場合、どのように書けばよいのかわからなかったんですが、答えは man builtins
にありました。
: [arguments]
No effect; the command does nothing beyond expanding arguments and performing
any specified redirections. The return status is zero.
:
がまさに「なにもしないをする」コマンドのようです。なので、先ほどの if
をこのように書き換えてみました。
$ cat if_sample.sh
if [ 条件式 ] ; then
#なにもしない(あとで実装予定)
:
else
if [ 条件式 ] ; then
exit 0
else
exit 1
fi
fi
echo 'successful'
実行してみると今度はうまくいきました。
$ bash if_sample.sh
successful