14
13

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 1 year has passed since last update.

bash / sh | 条件分岐の構文 ( if then else fi ) がどうしても脳に入ってこない時の考え方

Last updated at Posted at 2016-06-14

結論

シェルスクリプトの条件分岐は 「構文ではなく命令だ」 と考えた方が理解しやすいと思う。

問題

シェルスクリプトの if 構文は、よく分からない。
変な箇所にセミコロンが入ってきたりする。

どう理解すれば良いのか。

セミコロンを使わずに書く場合

セミコロンを使わなくても条件分岐は書ける。

if
  [ 1 -eq 1 ]
then
  echo 'You are the one!'
else
  echo 'You are one of the them!'
fi

ワンライナーで書く場合 ( ただし zsh に限る )

上記の例を zsh のワインライナーで書くと、次のようになる。
前の例から、改行を全てセミコロンに変えただけのものだ。

if; [ 1 -eq 1 ]; then; echo 'You are the one!'; else; echo 'You are one of the them!'; fi;

分解

つまり。
以下のすべては、命令として出来ていると考えることが出来る。

  • if
  • [ 1 -eq 1 ]
  • then
  • echo 'You are the one!'
  • else
  • echo 'You are one of the them!'
  • fi

これは全体で「構文」を作っているというよりも、あくまでも独立した1行ずつの命令であるというイメージ。
この命令同士が影響しあって、結果的に「条件分岐」が出来ている。

補足

コメント欄も参照のこと。

環境

  • sh 3.2

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

14
13
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
14
13

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?