你好,游客 登录 注册 搜索
背景:
阅读新闻

UNIX Shell控制结构—IF

[日期:2013-02-02] 来源:Linux社区  作者:bobo12082119 [字体:大 中 小]

第二种:if ... else ... fi,具体如下:
if [ expression ]
then
    statement(s) to be sxecuted if expression is true
else
    statement(s) to be sxecuted if expression is not true
fi

一个简单的实例

cat ifparam.sh
#!/bin/sh
if [ $# -lt 3 ]; then
  echo "Usage:`basename $0` arg1 arg2 arg3" >&2
  exit 1
fi
#EOF

echo "arg1:$1"
echo "arg1:$2"
echo "arg1:$3"
脚本注解:
1.$#表示参数输入的个数
2.basename $0打印文件的名称
3.若输入小于三个参数则,将输出一个信息,这个信息被当做是错误信息(>&2)。
执行脚本:
sh ifparam.sh scott tom
Usage:ifparam.sh arg1 arg2 arg3

sh ifparam.sh scott tom jim
arg1:scott
arg1:tom
arg1:jim

再来看一个测试:

cat ifeditor.sh
#!/bin/csh
#if [ -z $EDITOR ]①
#if [ -z "`echo $EDITOR`" ]③
#下面这种写法不能正确的计算出环境的值
#因为wc -c计算包括新的空的行
#if [ `echo $EDITOR | wc -c` -eq 0 ]②
if [ -z "`echo $EDITOR`" ]
 then
  echo "Your EDITOR environment is not set"
else
  echo "Using $EDITOR as the default editor"
fi
#EOF

sh ifeditor.sh
Your EDITOR environment is not set
这里使用三种方式去检测环境变量是否设置;
①直接报错:语法错误
②正确写法,使用test检测,-z表示如果为设置则长度为0返回值为true
③wc -c计算包括了空行,所以不准确

linux
相关资讯       Unix shell 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款