2
0

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 5 years have passed since last update.

ShellScriptでif-else文の否定のみの処理を短く書く

2
Last updated at Posted at 2019-03-21

2019/03/21 指摘対応
これでいいみたいです

# !/usr/bin/env sh
if ! { command1 || command2; }; then
    # commandのExitCode != 0の場合の処理
fi

安直に書くとこうなる

if command1 || command2; then
    : 
else
    # commandのExitCode != 0の場合の処理
fi

※以下は古い内容

結論

# !/usr/bin/env sh
if command;then :;else
    # commandのExitCode != 0の場合の処理
fi
# !/usr/bin/env sh
if command;then :;else
    # commandのExitCode != 0の場合の処理
fi

経緯

  • Shellのif文は終了コードによって分岐する
# !/usr/bin/env sh
if command;then
    # commandのExitCode == 0の場合の処理
else
    # commandのExitCode != 0の場合の処理
fi

  • testコマンド([])を使用しない場合、if文のみで否定演算はできない(と思う)
  • このため、終了コード != 0の場合のみ処理をしたい場合は冗長な書き方になる
# !/usr/bin/env sh
if command;then
    : # 「:」は何もしないコマンド
else
    # commandのExitCode != 0の場合の処理
fi

  • 短く書きたい場合は以下のようにできそう
  • thenの後ろにホワイトスペースが必要なことに注意
# !/usr/bin/env sh
if command;then :;else
    # commandのExitCode != 0の場合の処理
fi

  • 具体的には、OR条件で必要なコマンドが全て存在しない場合の条件分岐をしたかった
# !/usr/bin/env sh
if type curl &>/dev/null || type wget &>/dev/null;then :;else
    echo "required: curl or wget"
    exit 1
fi
2
0
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?