版权声明:本文为博主原创文章,转载请注明出处。 https://blog.csdn.net/twilight_karl/article/details/78373107
if 判断
单分支if条件语句
语法:
if [ 条件判断式 ];then
# do something
fi
或者
if [ 条件判断式 ]
then
# do something
fi
案例一,获取当前用户名,当然用 whoami
也可:
#!/bin/bash
test=`env | grep "USER" | cut -d "=" -f 2`
if [ test=="root" ];then
echo "This user is root"
fi
案例二,检查磁盘容量:
#!/bin/bash
rate=`df -h | grep "sda1" | awk '{ print $5 }' | cut -d "%" -f 1`
if [ $rate -gt "10" ];then
echo "/ is Full"
fi
PS:
- 条件判断式就是test命令判断,可以用test命令替代,中括号中间必须有空格
- -gt 当变量值为空时会报错
双分支if
语法:
if [ 条件判断式 ]
then
...
else
...
fi
案例三,判断目录的属性:
#!/bin/bash
read -t 30 -p "input a dir:" dir
if [ -d $dir ]
then
echo "This is a directory"
else
echo "no no no "
fi
案例四,判断tomcat服务是否开启:
#!/bin/bash
test=`ps aux | grep tomcat | grep -v grep`
if [ -n "$test" ]
then
echo "tomcat is running"
else
echo "tomcat is not running"
/etc/init.d/tomcat start
# service tomcat start 不建议使用
echo "tomcat is started"
fi
PS:
- if判断中的变量最好加上引号,因为如果变量的值中包含空格,将出现too many arguments
错误,所以还是写成 if [ -n "$test" ]
较安全
多分支if
语法:
if [ 条件判断 ]
then
# do something
elif [ 条件判断 ]
then
# do something
...
else
# do something
fi
案例五,简易计算器:
#!/bin/bash
read -p "please input num1:" num1
read -p "please input operator:" op
read -p "please input num2:" num2
if [ -z "$num1" -o -z "$num2" -o -z "$op" ]
then
echo "value shoud not be null"
exit 2
else
# 把所有数字替换成空,如果替换后不为空,则表示变量中不符合规范
test1=`echo $num1 | sed 's/[0-9]//g'`
test2=`echo $num2 | sed 's/[0-9]//g'`
if [ -n "$test1" -o -n "$test2" ];then
echo "数值格式错误"
exit 4
fi
if [ "$op" == "+" ]
then
result=$(($num1+$num2))
elif [ "$op" == "-" ]
then
result=$(($num1-$num2))
elif [ "$op" == "*" ]
then
result=$(($num1*$num2))
elif [ "$op" == "/" ]
then
let "result=$num1/$num2"
else
echo "operator is wrong"
exit 3
fi
fi
echo ${num1}${op}${num2}=${result}
案例六,判断文件类型:
#!/bin/bash
read -p "请输入文件或目录名:" path
if [ -z "$path" ]
then
echo "请输入内容!"
exit 10
elif [ ! -e "$path" ]
then
echo "文件或目录不存在"
exit 11
elif [ -f "$path" ]
then
echo "输入的是一个文件"
elif [ -d "$path" ]
then
echo "输入的是一个目录"
else
echo "输入的式其他类型的文件"
fi
case 分支
语法:
case $变量名 in
"值1")
// do something,变量的值等于值1
;;
"值2")
// do something,变量的值等于值2
;;
...
*)
// do something,变量的值与上面都不同
;;
esca
案例
#!/bin/bash
read -p "请输入 yes/no" result
case "$result" in
"yes")
echo "你输入的式yes"
;;
"no")
echo "你输入的是no"
;;
*)
echo "请输入正确的选择"
esac