testコマンド […] は、色々な状態を評価することができます。文字列比較・ファイル属性確認・整数の比較についてまとめました。
文字列比較
文字列 str1 と str2 を比較します。
演算子 | 条件 |
str1 = str2 | str1 が str2 と一致する |
str1 != str2 | str1 が str2 と一致しない |
str1 < str2 | str1 が str2 より小さい |
str1 > str2 | str1 が str2 より大きい |
-n str1 | str1 が nullではない |
-z str1 | str1 が 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 file | file が存在する |
-d file | file が存在し、かつディレクトリである |
-f file | file が存在し、かつ通常ファイルである |
-s file | file が存在し、空ではない |
-O file | file の所有者 |
file1 -nt file2 | file1 が file2よりも新しい |
file1 -ot file2 | file1 が 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