测试
测试结构
- 一个if/then结构测试一列命令的退出状态是否为0(因为依照惯例,0意味着命令执行成功),如果是0则会执行一个或多个命令。
- 有一个命令** [** ([左方括]是特殊字符). 它和test是同义词,因为效率的原因,它被内建在shell里。这个命令的参数是比较表达式或者文件测试,它会返回一个退出状态指示比较的结果(0表示真,1表示假)。
- [[]] 同样是测试命令,是一个比较关键字。
- if 命令不仅能测试由方括号括起来的条件,也能测试任何命令。
root@ubuntu:/home/newer# if cmp 1.txt keepme &>/dev/null; then echo "same"; else echo "diffrent";fi
diffrent
root@ubuntu:/home/newer# if grep -r dog 1.txt &>/dev/null; then echo "dog"; fi
dog
root@ubuntu:/home/newer# if [$abc] &>/dev/null; then echo "uninitialized variable is true"; else echo "uninitailized variable is fause"; fi
uninitailized variable is fause
#!/bin/bash
# 小技巧:
# 如果你不确定某一条件怎么被求值,
#+ 可以用一个if-test结构来测试.
echo
echo "Testing \"0\""
if [ 0 ] # 0
then
echo "0 is true."
else
echo "0 is false."
fi # 0为真.
echo
echo "Testing \"1\""
if [ 1 ] # 1
then
echo "1 is true."
else
echo "1 is false."
fi # 1为真.
echo
echo "Testing \"-1\""
if [ -1 ] # -1
then
echo "-1 is true."
else
echo "-1 is false."
fi # -1为真.
echo
echo "Testing \"NULL\""
if [ ] # NULL (空条件)
then
echo "NULL is true."
else
echo "NULL is false."
fi # NULL为假.
echo
echo "Testing \"xyz\""
if [ xyz ] # 字符串
then
echo "Random string is true."
else
echo "Random string is false."
fi # 任意字符串为true.
echo
echo "Testing \"\$xyz\""
if [ $xyz ] # 变量$xyz为null值, 但...
# 它只是一个未初始化的变量.
then
echo "Uninitialized variable is true."
else
echo "Uninitialized variable is false."
fi # 未初始化的变量为false.
echo
echo "Testing \"-n \$xyz\""
if [ -n "$xyz" ] # 进一步实验核实.
then
echo "Uninitialized variable is true."
else
echo "Uninitialized variable is false."
fi # 未始初化的变量为false.
echo
xyz= # 已初始化, 但设置成null值.
echo "Testing \"-n \$xyz\""
if [ -n "$xyz" ]
then
echo "Null variable is true."
else
echo "Null variable is false."
fi # Null值变量为假.
echo
# 什么时候"false"为真?
echo "Testing \"false\""
if [ "false" ] # "false"是一个字符串.
then
echo "\"false\" is true." #+ 它被测试为真.
else
echo "\"false\" is false."
fi # "false"为真.
echo
echo "Testing \"\$false\"" # 再来,未初始化的变量.
if [ "$false" ]
then
echo "\"\$false\" is true."
else
echo "\"\$false\" is false."
fi # "$false"变量为假.
# 现在, 我们取得了预期的效果.
# 如果我们测试未初始化的变量"$true"会发生什么?
echo
exit 0
结构
if [ condition1 ]
then
command1
command2
command3
elif [ condition2 ]
# 和else if相同
then
command4
command5
else
default-command
fi
等价的测试
#!/bin/bash
echo
if test -z "$1"
then
echo "No command-line arguments."
else
echo "First command-line argument is $1."
fi
echo
if /usr/bin/test -z "$1" # 和内建的"test"命令一样.
then
echo "No command-line arguments."
else
echo "First command-line argument is $1."
fi
echo
if [ -z "$1" ] # 和上面代码块的功能一样
# if [ -z "$1" 应该来说会运行, 但是...
#+ Bash给出错误说少了一个封闭的右方括.
then
echo "No command-line arguments."
else
echo "First command-line argument is $1."
fi
echo
if /usr/bin/[ -z "$1" ] # 同样和上面的代码块一样.
# if /usr/bin/[ -z "$1" # 工作, 但还是给出一个错误信息.
# # 注意:
# 这个已经在bash 3.x版本被修补好了。
then
echo "No command-line arguments."
else
echo "First command-line argument is $1."
fi
echo
exit 0