標籤:測試 test
#!/bin/bash
#1.整數比較子
#整數變數和整數常量比較
num1=15
[ "$num1" -eq 15 ] #測試num1是否等於15
echo $? ##退出狀態為0,表示num1等於15
[ "$num1" -eq 20 ] #測試num1是否等於20
echo $? ##退出狀態為1,表示num1不等於20
[ "$num1" -lt 15 ] ##測試num1是否小於15
echo $? ##退出狀態為1,表示num1不小於15
[ "$num1" -gt 15 ] ##測試num1是否大於15
echo $? ##退出狀態為1,表示num1不大於15
##兩個整數變數比較
first_num=99 ##深圳第一個變數為99
second_num=100 ##設定第二個變數為100
[ "$first_num" -gt "$second_num" ]
echo $? ##退出狀態為1,說明變數first_num值不大於變數second_num值
[ "$first_num" -eq "$second_num" ]
echo $? ##退出狀態為1,說明變數first_num值不等於變數second_num值
[ "$first_num" -lt "$second_num" ]
echo $? ##退出狀態為0,說明變數first_num值小於變數second_num值
#2.字串運算子
#字串比較運算
str1=""
test "$str1"
echo $? ##退出狀態為1,表示該字串為空白
test -n "$str1"
echo $? ##退出狀態為1,表示該字串為空白
test -z "$str1"
echo $? ##退出狀態為0,表示該字串為空白
#比較兩字串是否相等
type1="vi"
type2="vim"
[ "$type1" = "$type2" ] ##測試變數type1是否等於type2
echo $? ##退出狀態為1,說明變數type1不等於變數type2
[ "$type1" != "$type2" ] ##測試type1是否不等於type2
echo $? ##退出狀態為0,表示變數type1不等於變數type2
##空格造成測試結果不相等
str2="hello " ##賦值字串變數str2為"hello"
[ "$str2" = "hello" ] ##測試變數str2是否與"hello"相等
echo $? ##退出狀態為1,說明變數str2不等於"hello"
#大小寫區分
str3="Hello" ##賦值字串str3為"Hello"
[ "$str3" = "hello" ] ##測試變數str3是否與"hell"相等
echo $? ##退出狀態為1,說明變數str2不等於"hello"
##變數弱化造成的賦值結果不同
var1="007" ##給變數賦值,可以當作整數,也可以當作字串
[ "$var1" = "7" ] ##測試變數var1的值是否等於字串7
echo $? ##退出在為1,表示變數var1的值不等於字串7
[ "$var1" -eq "7" ] ##測試變數var1的值是否等於整數7
echo $? ##退出狀態為0,表示變數var1的值等於整數7
#3.檔案操作符
#判斷輸入的檔案是目錄還是目錄
ls ##顯示目前的目錄下的所有檔案
[ -d file_exam ] ##測試file_exam是否是目錄
echo $? ##退出狀態為1,說明file_examp不是目錄
[ -f file_exam ] ##測試file_exam是否是檔案
echo $? ##測試結果為0,說明file_exam是檔案
##測試檔案是否存在
ls
[ -e file_exam ] ##測試file_exam是否存在
echo $? ##突出狀態為0,不是檔案file-exam存在
[ -e file_exam1 ] ##測試檔案file_exam1是否存在
echo $? ##退出狀態為1,表示檔案file_exam1不存在
##測試檔案許可權
ls -l
[ -r file_exam ] ##測試檔案是否可讀
echo $?
[ -w file_exam ] ##測試檔案是否可寫
echo $?
[ -x file_exam ] ##測試檔案是否執行
echo $?
##顯示通過chmod命令增減檔案許可權
ls -l
[ -x file_exam ] ##測試檔案file_exam是否可執行
echo $? ##退出狀態為1,說明檔案file_exam不可執行
chmod a+x file_exam ##給檔案file_exam增加可執行許可權
[ -x file_exam ] ##再次測試檔案file_exam是否可執行
echo $? ##退出狀態為0,表示檔案file_exam現在可執行了
##4.邏輯運算子
#邏輯非
ls
[ ! -e file_exam ] ##使用邏輯非測試一個存在的檔案
echo $? ##腿子狀態為1,說明檔案file_exam不存在是假的
[ ! -e file_exam ] ##使用邏輯非測試一個不存在的檔案
echo $? ##退出狀態為0,說明檔案file_exam存在是假的
##邏輯與
ls -l
[ -e file_exam -a -x file_exam ] ##測試檔案file_exam是否存在且可執行
echo $? ##退出狀態為0,說明檔案file_exam存在且可執行
chmod a-x file_exam ##將檔案file_exam的可執行許可權去除
ls -l
[ -e file_exam -a -x file_exam ] ##再次測試檔案file_exam是否存在且可執行
echo $? ##退出狀態為1,說明檔案file_exam不存在或不可執行
##邏輯或
integer1=15
[ "$integer1" -lt 20 -o "$integer1" -gt 30 ] ##測試整數變數integer1是否小於20或大於30
echo $? ##退出狀態為0,表示整數變數integer小於20或大於30
[ "$integer1" -lt 10 -o "$integer1" -gt 20 ] ##測試整數變數integer1是否小於10或大於20
echo $? ##測試狀態為1,表示整數變數integer1大於10且小於20
本文出自 “盡夜” 部落格,請務必保留此出處http://endmoon.blog.51cto.com/8921900/1616632
shell指令碼的測試用法