test 命令的基本格式為:test 測試條件,它常用來判斷字符串、整數與文件屬性。
字符串測試(注意空格):
test str1 == str2 測試兩字符串是否相等
test str1 != str2 測試兩字符串是否不相等
test str1 測試字符串是否不為空
test -n str1 測試字符串是否不為空
test -z str1 測試字符串是否為空
整數測試:
test int1 -eq int2 測試整數是否相等
test int1 -ge int2 測試 int1 是否 >= int2
test int1 -gt int2 測試 int1 是否 > int2
test int1 -le int2 測試 int1 是否 <= int2
test int1 -lt int2 測試 int1 是否 < int2
test int1 -ne int2 測試兩數是否不相等
文件測試:
test -d file 指定文件是否為目錄
test -f file 指定文件是否為常規文件
test -x file 指定文件是否可執行
test -r file 指定文件是否可讀
test -w file 指定文件是否可寫
test -a file 指定文件是否存在
test -s file 指定文件大小是否非 0
測試語句一般不單獨使用,而是作為 if 語句的判斷條件:
if test "hello" == "hello" ;then
commands....
fi
# 上面語句也可簡化為(注意 [] 與內容之間要留空格)
if [ "hello" == "hello" ];then
...
看一段綜合示例:
#!/bin/bash
if test "hello" == "hello" ;then
echo "equals"
else
echo "not equals"
fi
if test -z "" ;then
echo "str is null"
fi
if test -n "" ;then
echo "str is not null"
fi
if test "9" ;then
echo "not null"
else
echo "null"
fi
#easy way
if [ "hello" == "hello" ];then
echo "equals"
else
echo "not equals"
fi
if [ -f /root/test/test1 ];then
echo "test1 is a file"
elif [ -d /root/test/test1 ];then
echo "test1 is a dir"
else
echo "i don't know the result"
fi
需要特別提醒的是,方括號 [ ] 屬於命令,因此它與兩側內容之間必須保留空格,這是初學者最常踩的坑之一。