- 论坛徽章:
- 2
|
菜菜请教:这个是个什么文件?
使用test命令进行进行条件测试
格式: test conditions
test在以下四种情况下使用: a. 字符比较 b.两个整数值的比较
c. 文件操作,如文件是否存在及文件的状态等
d. 逻辑操作,可以进行and/or,与其他条件联合使用
a. 测试字符数据: shell变量通常民政部下均作为字符变量
str1 = str2 二者相长,相同
str1 != str2 不同
-n string string不为空(长度不为零)
-z string string为空
string string不为空
例:
$ str1=abcd #在含有空格时必须用引号括起来
$ test $str1=abcd
$ echo $?
0
$ str1="abcd "
$ test $str1=abcd
$ echo $?
1
Note: 在test处理含有空格的变量时最好用引号将变量括起来,否则会出现错误的
结果,
因为shell在处理命令行时将会去掉多余的空格,而用引号括起来则可以防止
shell去掉这些空格.
例:
$ str1=" "
$ test $str1
$ echo $?
1
$ test "$str1"
$ echo $?
0
$ test -n $str1
test: argument expected
$ test -n "$str1"
$ echo $?
0
$
b. 整数测试: test与expr相同,可以将字符型变量转换为整数进行操作,expr进行
整数的算术运算,而test则进行逻辑运算.
表达式 说明
---------------------------------------
int1 -eq int2 相等?
int1 -ne int2 不等?
int1 -gt int2 int1 >; int2 ?
int1 -ge int2 int1 >;= int2 ?
int1 -lt int2 int1 < int2 ?
int1 -le int2 int1 <= int2 ?
例:
$ int1=1234
$ int2=01234
$ test $int1 -eq $int2
$ echo $?
0
c. 文件测试:检查文件状态如存在及读写权限等
-r filename 用户对文件filename有读权限?
-w filename 用户对文件filename有写权限?
-x filename 用户对文件filename有可执行权限?
-f filename 文件filename为普通文件?
-d filename 文件filename为目录?
-c filename 文件filename为字符设备文件?
-b filename 文件filename为块设备文件?
-s filename 文件filename大小不为零?
-t fnumb 与文件描述符fnumb(默认值为1)相关的设备是一个终端设备?
d. 测试条件之否定,使用!
例:
$ cat /dev/null >; empty
$ test -r empty
$ echo $?
0
$ test -s empty
1
$ test ! -s empty
$ echo $?
0
e. 测试条件之逻辑运算
-a And
-o Or
例: $ test -r empty -a -s empty
$ echo $?
1
f. 进行test测试的标准方法
因为test命令在 shell编程中占有很重要的地位,为了使shell能同其他编程语言
一样
便于阅读和组织, Bourne Shell在使用test测试时使用了另一种方法:用方括号将
整个
test测试括起来:
$ int1=4
$ [ $int1 -gt 2 ]
$ echo $?
0
例: 重写unload程序,使用test测试
#!/bin/sh
#unload - program to backup and remove files
#syntax: unload directory
#check arguments
if [ $# -ne 1 ]
then
echo "usage: $0 directory"
exit 1
fi
#check for valid directory name
if [ ! -d "$1" ]
then
echo "$1 is not a directory"
exit 2
fi
cd $1
ls -a | cpio -o >; /dev/rmt/0h
if [ $? -eq 0 ]
then
rm -rf *
else
echo "A problem has occured in creating backup"
echo "The directory will not be ereased"
echo " lease check the backup device"
exit 3
fi
# end of unload
在如上示例中出现了exit, exit有两个作用:一是停止程序中其他命令的执行,二
是
设置程序的退出状态 |
|