歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> SHELL編程 >> Linux shell入門之變量測試

Linux shell入門之變量測試

日期:2017/3/1 9:26:21   编辑:SHELL編程

格式: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

執行效果:

Linux Shell在while中用read從鍵盤輸入 http://www.linuxidc.com/Linux/2015-06/118831.htm

Linux Shell 程序調試 http://www.linuxidc.com/Linux/2015-07/119880.htm

Linux Shell腳本面試25問 http://www.linuxidc.com/Linux/2015-04/116474.htm

Linux/Unix Shell 參數傳遞到SQL腳本 http://www.linuxidc.com/Linux/2013-03/80568.htm

Shell腳本中參數傳遞方法介紹 http://www.linuxidc.com/Linux/2012-08/69155.htm

Shell腳本傳遞命令行參數 http://www.linuxidc.com/Linux/2012-01/52192.htm

Linux Shell 通配符、轉義字符、元字符、特殊字符 http://www.linuxidc.com/Linux/2014-10/108111.htm

Copyright © Linux教程網 All Rights Reserved