Chinaunix首页 | 论坛 | 博客
  • 博客访问: 97967
  • 博文数量: 28
  • 博客积分: 1435
  • 博客等级: 上尉
  • 技术积分: 265
  • 用 户 组: 普通用户
  • 注册时间: 2010-04-26 11:40
文章分类

全部博文(28)

文章存档

2017年(1)

2012年(1)

2011年(6)

2010年(20)

我的朋友

分类:

2010-05-11 11:03:45

测试一般用在条件判断结构:
if [something_to_test]
then do_something
else do_something_else
fi

其中something_to_test就是测试语句。在shell中一般有一下几种命令:
  1. test:
  2. [.. ]
  3. [[.. ]]
1和2是相同的,3是前两者的增强版。[[..]]可以避免很多[..]中的逻辑错误,尤其是&&, ||, <, and >的时候尽量使用[[..]],但是这些情况都很少碰到,因此大多数情况下这3者的效果是一样的。

test常用选项:
字符串比较:
       -n STRING
              the length of STRING is nonzero

       STRING equivalent to -n STRING

       -z STRING
              the length of STRING is zero

       STRING1 = STRING2
              the strings are equal

       STRING1 != STRING2
              the strings are not equal

整数比较:
       INTEGER1 -eq INTEGER2
              INTEGER1 is equal to INTEGER2

       INTEGER1 -ge INTEGER2
              INTEGER1 is greater than or equal to INTEGER2

       INTEGER1 -gt INTEGER2
              INTEGER1 is greater than INTEGER2

       INTEGER1 -le INTEGER2
              INTEGER1 is less than or equal to INTEGER2

       INTEGER1 -lt INTEGER2
              INTEGER1 is less than INTEGER2

       INTEGER1 -ne INTEGER2
              INTEGER1 is not equal to INTEGER2

还可以用来测试file的类型,举一个例子,其余参考man test:
-d file 测试file是否存在且是一个目录

例子:

1 #!/bin/bash
  2
  3 if test -n "$1"
  4 then
  5 echo "the first commond_line argument is $1"
  6 else
  7 echo "no commond_line argument"
  8 fi
  9
 10 if [ -z "$1" ]
 11 then
 12 echo "no commond_line argument"
 13 else
 14 echo "the first commond_line argument is $1"
 15 fi
 16
 17 file=test.sh
 18 if [[ -e "$file" ]]
 19 then
 20 echo "file $file exist"
 21 else
 22 echo "file $file not exist"
 23 fi    

执行结果:

lzj@lzj-laptop:~/documents/abs_guide$ ./test.sh kkk
the first commond_line argument is kkk
the first commond_line argument is kkk
file test.sh exist
                                             


阅读(383) | 评论(0) | 转发(0) |
0

上一篇:VI命令手册

下一篇:cscope命令备忘

给主人留下些什么吧!~~