设为首页 加入收藏

TOP

UNIX Shell控制结构—IF
2014-11-24 08:27:22 来源: 作者: 【 】 浏览:0
Tags:UNIX Shell 控制 结构

流控制(Decision Making)
IF语句有三种格式:
第一种:if ... fi statement


下面是一个实例:


cat if1.sh
#!/bin/sh
a=10
b=20
#①
if [ $a -eq $b ]; then
echo "a is equal to b";
fi
if [ $a -gt $b ]; then
echo "a is great than b";
fi
#②
if [ $a -lt $b ]
then
echo "a is less than b";
fi
# the EOF


注意:
①条件和处理命令分开的一种写法:
if 条件; then
处理命令
fi
②条件和处理命令分开的另一种写法:
if 条件
then
处理命令
fi
这里需要根据个人习惯去选择。


上面的例子中,变量的值是赋死了的,若要给此脚本传递两个参数,可做如下修改:


cat if1.sh
#!/bin/sh
# a=10
# b=20
if [ $1 -eq $2 ]; then
echo "the first number is equal to the second";
fi
if [ $1 -gt $2 ]; then
echo "the first number is great than the second";
fi
if [ $1 -lt $2 ]
then
echo "the first number is less than the second";
fi
# the EOF


给脚本传递参数,只需要在sh命令后面添加即可,使用空格隔开:


sh if1.sh 1 2
the first number is less than the second
sh if1.sh 12 1
the first number is great than the second
sh if1.sh 1 1
the first number is equal to the second


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇Unix Shell控制结构—CASE 下一篇Linux C语言:程序运行时动态加载..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Python 数据分析与可 (2025-12-26 21:51:20)
·从零开始学Python之 (2025-12-26 21:51:17)
·超长干货:Python实 (2025-12-26 21:51:14)
·为什么 Java 社区至 (2025-12-26 21:19:10)
·Java多线程阻塞队列 (2025-12-26 21:19:07)