標籤:shell linux ubuntu 變數測試
格式:test 測試條件
字串測試:注意空格:test str1 == str2 測試字串是否相等test str1 != str2 測試字串是否不相等test str1 測試字串是否不為空白test -n str1 測試字串是否不為空白test -z str1 測試字串是否為空白整數測試test int1 -eq int2 測試整數是否相等test int1 -ge int2 測試int1是否>=int2test int1 -gt int2 測試int1是否>int2test int1 -le int2 測試int1是否<=int2test int1 -lt int2 測試int1是否<int2test 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" ;thencommands....fi上面語句也可簡化為(注意[]與"之間的空格)if [ "hello" == "hello" ];then....
看一段代碼:
#!/bin/bashif test "hello" == "hello" ;thenecho "equals"elseecho "not equals"fiif test -z "" ;thenecho "str is null"fiif test -n "" ;thenecho "str is not null"fiif test "9" ;thenecho "not null"elseecho "null"fi#easy wayif [ "hello" == "hello" ];thenecho "equals"elseecho "not equals"fiif [ -f /root/test/test1 ];thenecho "test1 is a file"elif [ -d /root/test/test1 ];thenecho "test1 is a dir"elseecho "i don‘t know the result"fi
執行效果:
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
shell入門之變數測試