1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

シェルスクリプトの「if」で「なにもしないをする」をやりたい場合

Last updated at Posted at 2021-08-01

シェルスクリプトの 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

参考URL

1
1
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?