bash/比較演算子

August 03, 2021

bash の比較演算子の意味 - enokitech

bash であれば [[! -d /var/tmp]] のような 2 重カッコを使うことで、否定ができる

演算子 英語 記号
-lt Less than <
-gt Greater than >
-le Less than or Equal to <=
-ge Greater than or Equal to >=
-eq Equal to =
-ne Not equal to !=

文字列比較

= 左項と右項が同一文字列の場合真
!= でない場合真
str 文字列が null でない場合真
-n 文字列が null でない場合真(not zero)
-z の場合真(zero)
if [ "$1" = "$2" ]; then

ファイルに関するオプション

オプション 効果
-d ディレクトリなら真
-f 普通のファイルなら真
-r 読み出し可能なら真
-s サイズが 0 より大きければ真
-w 書き込み可能なら真
-x 実行可能なら真
if [ -f "file1" ]; then

条件式を論理演算するオプション

オプション 効果
-a 左項条件式と右項条件式のどちらも真の場合真(and)
-o どちらかが真の場合真(or)
! 条件式の否定(not)
() ()の中の条件式を優先する
if [ $1 -lt $2 -a \( $1 -lt $4 \) -o $2 -lt $3

Profile picture

Written by tin-machine 技術関連のメモ Twitter