シェルスクリプト testコマンド 条件評価 スクリプトの書き方

スポンサーリンク

testコマンド […] は、色々な状態を評価することができます。文字列比較・ファイル属性確認・整数の比較についてまとめました。

文字列比較

文字列 str1 と str2 を比較します。

演算子条件
str1 = str2str1 が str2 と一致する
str1 != str2str1 が str2 と一致しない
str1 < str2str1 が str2 より小さい
str1 > str2str1 が str2 より大きい
-n str1str1 が nullではない
 -z str1str1 が null
文字列の比較演算子

サンプル

例1. 文字列比較

#! /bin/sh

AAA="aaa"
BBB="bbb"

if [ ${AAA} != ${BBB} ]; then
  echo 'AAA and BBB are different"
fi
echo "done"
AAA and BBB are different
done

例2. 文字列のnullチェック

#! /bin/sh

AAA=

if [ -z ${AAA} ]; then
  echo "AAA is null"
fi
echo "done"
AAA is null
done

ファイル属性確認

ファイル file について存在や属性をチェックします。

演算子条件
-e filefile が存在する
-d filefile が存在し、かつディレクトリである
-f filefile が存在し、かつ通常ファイルである
-s filefile が存在し、空ではない
-O filefile の所有者
file1 -nt file2file1 が file2よりも新しい
file1 -ot file2file1 が file2よりも新しい
ファイルについての判定

サンプル

例1. ファイルの存在チェック

#! /bin/sh

if [ -e $1 ]; then
echo "$1 is exist"
fi
echo "done"
sample_shell.sh aaa.txt
aaa.txt is exist
done

整数の比較

整数 num1 と num2 を比較します。

演算子比較
-ltより小さい
-le以下
-eq等しい
-ge以上
-gtより大きい
-ne等しくない
整数の比較演算子

サンプル

例1. 整数の比較

#! /bin/sh

AAA=3
BBB=5

if [ ${AAA} -lt ${BBB} ]; then
echo 'AAA is small'
fi
echo "done"
AAA is small
done

タイトルとURLをコピーしました