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

UNIX Shell控制结构—IF

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

第三种:if ... elif ... fi,具体如下:

if [ expression 1 ]; then
  statement(s) to be sxecuted if expression 1 is true
elif [ expression 2 ]; then
  statement(s) to be sxecuted if expression 2 is true
elif [ expression 3 ]; then
  statement(s) to be sxecuted if expression 3 is true
else
  statement(s) to be sxecuted if no expression is true
fi

下面是一个比较两个数字大小的例子:

cat elif.sh
#!/bin/sh
if [ $1 == $2 ]; then
  echo "the first number is equal to the next"
elif [ $1 -gt $2 ]; then
  echo "the first number is great than the next"
elif [ $1 -lt $2 ]; then
  echo "the first number is great than the next"
else
  echo "None of the condition met"
fi
#EOF

当不输入任何数字的时候,也就是为空,结果如下:
sh elif.sh
the first number is equal to the next
当输入数字的时候,如下:
sh elif.sh 10 20
elif.sh: test: unknown operator ==
这种情况,我们可以将其错误信息输入到一个文件当中,如下:
sh elif.sh 10 20 > log.txt 2>&1
cat log.txt
elif.sh: test: unknown operator ==
当将“==”号修改为-eq,结果如下:
sh elif.sh 10 20
the first number is less than the next

下面是一个if的实例,包括这三种命令格式;
脚本的作用是创建一个目录,如果不输入任何值,则打印脚本的作用说明;
输入则提示是否创建,输入非提示,则报错误,否则按提示走。

#!/bin/sh
DIR=$1
if [ "$DIR" = "" ]; then
  echo "Usage:`basename $0` directory to create" >&2
  exit 1
fi


if [ -d $DIR ]; then
  echo "Directory $DIR exists"
else
  echo "The Directory does exist"
  echo -n "Create it now?[y..n]:"
  read ANS
  if [ "$ANS" = "y" ] || [ "$ANS" = "Y" ]; then
      echo "creating now"
      mkdir $DIR > log.txt 2>&1
      if [ $? -ne 0 ]; then
        echo "Errors creating the directory $DIR" >&2
        exit 1
      fi
      echo "Creating successful"
  elif [ "$ANS" = "n" ] || [ "$ANS" = "N" ]; then
      echo "Giving up creating directory $DIR"
  else
      echo "Bad input"
  fi
fi
#EOF

1.不输入参数
sh ifmkdir.sh
Usage:ifmkdir.sh directory to create
2.输入一个存在的目录,提示目录已经存在:
sh ifmkdir.sh test
Directory test exists
查看确实有test目录:
[ -d test ]
echo $?
0
创建test1目录:sh ifmkdir.sh test1
The Directory does exist
Create it now?[y..n]:y
creating now
Creating successful
3.执行脚本,但不想创建目录:
sh ifmkdir.sh test2
The Directory does exist
Create it now?[y..n]:n
Giving up creating directory test2
4.执行脚本时,不按照提示输入:
sh ifmkdir.sh test2
The Directory does exist
Create it now?[y..n]:d

Bad input

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

       

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