本文共 3279 字,大约阅读时间需要 10 分钟。
语法:
if [ 条件判断式 ];then # do somethingfi
或者
if [ 条件判断式 ] then # do somethingfi
案例一,获取当前用户名,当然用 whoami
也可:
#!/bin/bashtest=`env | grep "USER" | cut -d "=" -f 2`if [ test=="root" ];then echo "This user is root"fi
案例二,检查磁盘容量:
#!/bin/bashrate=`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 [ 条件判断式 ] then ... else ...fi
案例三,判断目录的属性:
#!/bin/bashread -t 30 -p "input a dir:" dirif [ -d $dir ] then echo "This is a directory" else echo "no no no "fi
案例四,判断tomcat服务是否开启:
#!/bin/bashtest=`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 [ 条件判断 ] then # do somethingelif [ 条件判断 ] then # do something...else # do somethingfi
案例五,简易计算器:
#!/bin/bashread -p "please input num1:" num1read -p "please input operator:" opread -p "please input num2:" num2if [ -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 fifiecho ${num1}${op}${num2}=${result}
案例六,判断文件类型:
#!/bin/bashread -p "请输入文件或目录名:" pathif [ -z "$path" ] then echo "请输入内容!" exit 10elif [ ! -e "$path" ] then echo "文件或目录不存在" exit 11elif [ -f "$path" ] then echo "输入的是一个文件"elif [ -d "$path" ] then echo "输入的是一个目录"else echo "输入的式其他类型的文件"fi
语法:
case $变量名 in "值1") // do something,变量的值等于值1 ;; "值2") // do something,变量的值等于值2 ;; ... *) // do something,变量的值与上面都不同 ;;esca
案例
#!/bin/bashread -p "请输入 yes/no" resultcase "$result" in "yes") echo "你输入的式yes" ;; "no") echo "你输入的是no" ;; *) echo "请输入正确的选择"esac