0
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.

シェルスクリプト bash 条件式

Posted at
条件式 [[]]

bash では条件式 [[]] を使って、条件を評価することが可能。

conditions1.sh
num=10

if [[ "$num" -ge 5 && "$num" -le 15 ]]
then
  echo "Between 5 and 15."
fi

char="abc"

if [[ "$char" == "abc" ]]
then
  echo "char is abc."
fi

if [[ "$char" != "xyz" ]]
then
  echo "char is not xyz."
fi
test コマンドの [] に似ている

非常によく似ているが、使用できる演算子に一部違いがある。

条件式[[]] test コマンド[]
条件式1 && 条件式2 条件式1 -a 条件式2
条件式1 ll 条件式2 条件式1 -o 条件式2

上記と同じ意味を持つコマンドを test コマンドで書き直すと、以下のようになる。

conditions2.sh
num=10

if [ "$num" -ge 5 -a "$num" -le 15 ]
then
  echo "Between 5 and 15."
fi

char="abc"

if [ "$char" == "abc" ]
then
  echo "char is abc."
fi

if [ "$char" != "xyz" ]
then
  echo "char is not xyz."
fi

ただ、シェルスクリプトの互換性(bash以外では使えないケース)を考慮すると、初めから test コマンドで書く方がよさそう。

0
0
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
0
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?