Chinaunix首页 | 论坛 | 博客
  • 博客访问: 281358
  • 博文数量: 38
  • 博客积分: 706
  • 博客等级: 上士
  • 技术积分: 390
  • 用 户 组: 普通用户
  • 注册时间: 2012-06-05 09:09
文章分类

全部博文(38)

文章存档

2013年(23)

2012年(15)

我的朋友

分类: Python/Ruby

2012-11-29 10:34:24

       近日不少朋友问到shell的用法,本着技术是分享的原则,基本上都一一作答。一来为了巩固自己的知识,而来帮人解惑。 还是我常说的一句话,shell写法重在思路,有思路,剩下的就是拼凑。。好了,不罗嗦,开始今天的if部分的解释,这里顺便说明一下,我本菜鸟,目前连运维都不是,如果有大牛路过,还请海涵,莫怪我误人子弟,呵呵。。。

 
if 语句格式
 ------------------------
 
if 条件

then

  Command

else

  Command

fi
--------------------------- 
这是基本格式。方便了解我举个例子
read a
if [ -n $a ];
then
echo “success”
else
echo “Error”
fi
-------------------------------
以上是if的基本格式。纯手写例子,符号可能有所差异,各位调试的时候适当修改。

根据上面的语句,我们还有扩展方式

------------------------
 
if 条件

then

  Command

elif

  Command

else
        Command
fi

---------------------------  
这里和上面差不多,大家可对比的看下。。

下面开始介绍if中的各类表达式 

 
字符串判断:

[ string1 = string2 ]    or    两个字符串相等时返回true.
[ string1 == string2 ]

[ string1 != string2 ]         两个字符串不等时返回true.
[ string ]                          string非空时返回true.
[ -z string ]                      为空时返回true.
[ -n string ]                      为非空时返回true.

逻辑判断:(cond1可以包含元字符)
[ string1 -a string2 ] or     string1string2都非空时
[[ cond1 && cond2 ]]        cond1cond2都为true

[ string1 -o string2 ] or     string1string2为非空时
[[ cond1 || cond2 ]]          cond1cond2true.

[ ! string ] or                    string为空

[[ !cond ]]                        condfalse.

整数判断:
[ int1 -eq int2 ]                int1等于int2
[ int1 -ne int2 ]                int1不等于int2
[ int1 -gt int2 ]                 int1大于int2
[ int1 -ge int2 ]                int1大于等于int2
[ int1 -lt int2 ]                  int1小于int2
[ int1 -le int2 ]                 int1小于等于int2


文件判断

[ file1 -nt file2 ]               file1file2
[ file1 -ot file2 ]               file1file2


文件检验:

[ -d $file ] or                   表示判断目录是否存在
[[ -d $file ]]

[ -e $file ] or                   表示判断文件是否存在
[[ -e $file ]]

[ -f $file ] or                   表示判断非目录普通文件是否存在
[[ -f $file ]]

[ -s $file ] or                  表示判断文件存在并且非0.
[[ -s $file ]]

[ -L $file ] or                  表示判断为链接符号存在
[[ -L $file ]]

[ -r $file ] or                  表示判断文件存在并且可读.
[[ -r $file ]]

[ -w $file ] or                 表示判断文件存在并且可写.
[[ -w $file ]]

[ -x $file ] or                 表示判断文件存在并且可执行.

[[ -x $file ]]  

 

 以上就是if语句常用方法。暂时就写到这,后续可能会继续增加,视情况而定。
阅读(1865) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~