Skip to content

Instantly share code, notes, and snippets.

@ShinNakamura
Created March 11, 2021 23:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ShinNakamura/f1cdfb891a3f2e9a9b6b365d4f83620c to your computer and use it in GitHub Desktop.
Save ShinNakamura/f1cdfb891a3f2e9a9b6b365d4f83620c to your computer and use it in GitHub Desktop.
[bash] if の構文を意味で理解する

[bash] if の構文を意味で理解する

if 制御構造は次のように複数の書き方がある(動作は全て同じ)。

#! /bin/sh
 
my_file="some.file"
 
# if 1
if test -f $my_file
then
    echo "$my_file Exists."
else
    echo "Not Found ${my_file}."
fi
 
# if 2
if test -f $my_file; then
    echo "$my_file Exists."
else
    echo "Not Found ${my_file}."
fi
 
# if 3
if [ -f $my_file ]; then
    echo "$my_file Exists."
else
    echo "Not Found ${my_file}."
fi

丸暗記でもいいけど、意味を理解したほうがベター。

まず if は直後にくる「コマンド」の返り値で真偽を判断する。

上の例で test -f $my_file はコマンド呼び出し。

コマンドを呼ぶときの原則

シェルスクリプトは行指向のインタプリタを使ってるから「改行」には「コマンドの入力を終了したよ」という行を改める以上の意味がある。 だから、コマンドが複数行にまたがるときは改行する前に「\」を入れる。

test -f $my_file はこれでひとつのコマンドだから、もし if test -f $my_file then と書いてしまうと 「then」というキーワードも test の引数であると見做されてしまう。

そういうわけで、if test -f $my_file; then と書いて、コマンドと then; で区別してあげる必要がある。

[ ... ]

次に if [ -f $my_file ]; then[ ... ]test コマンドの糖衣構文(シンタックスシュガー)。

すると ;then の前に必要。

[] の前後に半角スペースが一つ以上必要なのはなぜ?

[ ... ]もコマンドだから。

シェルスクリプトでは、コマンドや引数同士は半角スペースで区切る。

付け加えておくと、[ ... ]; この最後のセミコロンは改行と等しく ひとつのコマンド呼び出しの終了を表しているだけなので、]; の間にスペースは不要。

参考図書

入門UNIXシェルプログラミング―シェルの基礎から学ぶUNIXの世界 単行本 – 2003/2/1 ブルース・ブリン (著), Bruce Blinn (著), 山下 哲典 (翻訳)

https://amzn.to/3ew9NM0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment