2
2

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.

bashのif文を書くときの注意点6選

Posted at

完全に間違った書き方

hoge.sh
# !/bin/bash
hoge="hoge"
if [${hoge} eq "hoge"]
    echo "do something"
else if [${hoge} eq "fuga"]
    echo "do something else"
else
    echo "do nothing"

正しい書き方

hoge.sh
# !/bin/bash
hoge="hoge"
if [ "${hoge}" = "hoge" ] ; then
    echo "do something"
elif [ "${hoge}" = "fuga"] ; then
    echo "do something else"
else
    echo "do nothing"
fi

間違いポイント1 fiがない

これは基本だがたまにやる。

間違いポイント2 [はコマンド

[ はコマンドなので、前後にはスペースが必要

間違いポイント3 ;thenがない

たまに忘れる

間違いポイント4 elif

else ifではなくelif。そしてこちらも;thenが必要

間違いポイント5 eq

eqではなく-eqが正しいのと、これは数値比較に使うもので、文字列比較には-eqではなく=を使う。

間違いポイント6 ${hoge}

条件式で使う変数にはダブルクォーテーションをつける
変数が文字列と認識されず、"unary operator expected"というエラーが環境によっては出る。

2
2
0

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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?