示例1:使用传参的方式实现两个整数的比较:
#!/bin/bash
#
read -p "Please input second number: " num1 num2if [ $num1 -lt $num2 ]thenecho "$num1 is less than $num2."exit
fiif [ $num1 -eq $num2 ]thenecho "$num1 is equal to $num2."exit
fiif [ $num1 -gt $num2 ]thenecho "$num1 is greater than $num2."exit
fi
示例2:使用read输入的方式实现两个整数的比较:
[root@vm1 scripts]# cat if3.sh
#!/bin/bash
#
#read -p "Please input second number: " num1 num2
num1=$1
num2=$2if [ $num1 -lt $num2 ]thenecho "$num1 is less than $num2."exit
fiif [ $num1 -eq $num2 ]thenecho "$num1 is equal to $num2."exit
fiif [ $num1 -gt $num2 ]thenecho "$num1 is greater than $num2."exit
fi
说明:
1)read读入和命令行传参是两种输入内容的方法,不要混用。
2)缺点是复杂、逻辑还不够清晰,那么有没有更好的方法呢?当然有的,见后面的分支if的实现。
示例3: 开发shell脚本,实现如果/server/scripts下面存在if3.sh就输出到屏幕。注意:如果执行脚本后发现脚本if3.sh不存在,就自动创建这个if3.sh的脚本。
[root@vm1 scripts]# cat if6.sh
#!/bin/sh
#
path=/server/scripts
file=if7.shif [ ! -d "$path" ]thenmkdir -p $pathecho "$path dir is not exist. already create it."
fiif [ ! -f "$path/$file" ]thentouch $path/$fileecho "$path/$file is not exist. already create it."exit
fils -l $path/$file
运行脚本进行测试:
[root@vm1 scripts]# sh if6.sh
/server/scripts/if7.sh is not exist. already create it.
[root@vm1 scripts]# sh if6.sh
-rw-r--r-- 1 root root 0 Jul 31 23:44 /server/scripts/if7.sh
[root@vm1 scripts]#
示例4:开发脚本判断系统剩余内存大小,如果低于100M就邮件告警。测试告警成功后系统定时任务每3分钟执行一次检查。