Shell Keyword 「if」

type if

執行

$ type if

顯示

if is a shell keyword

help if

執行

$ help if

顯示

if: if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMMANDS; ] fi
    Execute commands based on conditional.

    The `if COMMANDS' list is executed.  If its exit status is zero, then the
    `then COMMANDS' list is executed.  Otherwise, each `elif COMMANDS' list is
    executed in turn, and if its exit status is zero, the corresponding
    `then COMMANDS' list is executed and the if command completes.  Otherwise,
    the `else COMMANDS' list is executed, if present.  The exit status of the
    entire construct is the exit status of the last command executed, or zero
    if no condition tested true.

    Exit Status:
    Returns the status of the last command executed.

範例 001

if true; then :; fi

寫成多行

if true; then
    :;
fi

範例 002

if true; then echo 'yes'; fi

寫成多行

if true; then
    echo 'yes';
fi

顯示

yes

範例 003

if false; then echo 'm1'; else echo 'm2'; fi

寫成多行

if false; then
    echo 'm1';
else
    echo 'm2';
fi

範例 004

if false; then echo 'm1'; elif true; then echo 'm2'; fi

寫成多行

if false; then
    echo 'm1';
elif true; then
    echo 'm2';
fi

範例 005

if false; then echo 'm1'; elif false; then echo 'm2'; else echo 'm3'; fi

寫成多行

if false; then
    echo 'm1';
elif false; then
    echo 'm2';
else
    echo 'm3'; 
fi