if分支结构
用法1:
if CONDITION; then
statement
statement
...
fi
CONDITION的写法:
COMMAND
[ expression ]
expression表达式:
数学表达式
字符表达式
文件目录表达式
数学表达式:
[ number1 -eq number2 ]
[ number1 -ne number2 ]
[ number1 -gt number2 ]
[ number1 -ge number2 ]
[ number1 -lt number2 ]
[ number1 -le number2 ]
用法2
if CONDITION; then
statement
statement
...
else
statement
statement
fi
多个条件的写法:
AND [ condition1 -a condition2 ] [ condition1 ] && [ condition2 ]
OR [ condition1 -o condition2 ] [ condition1 ] || [ condition2 ]
编写脚本, 判断当前系统时间的小时数字
9--11 morning
12--14 noon
15---18 afternoon
night
编写脚本
hour=`date +%H`
if [ $hour -ge 9 -a $hour -le 11 ]; then
echo "Morning"
elif [ $hour -ge 12 -a $hour -le 14 ]; then
echo "Noon"
elif [ $hour -ge 15 -a $hour -le 18 ]; then
echo "Afternoon"
else
echo "Night"
fi
[ expression ]
字符表达式
[ str1 == str2 ]
[ str1 != str2 ]
[ -z str1 ] 判断字符串是否为空的
编写脚本
#!/bin/bash
read -p "请输入密码:" pwd1
read -p "请再次输入密码:" pwd2
if [ "$pwd1" == "$pwd2" ]; then
echo "密码设置成功"
else
echo "密码不一致,请重试"
fi
运行后的结果
student@student-VirtualBox:/tmp$ ./t1.sh
请输入密码:123
请再次输入密码:123
密码设置成功
student@student-VirtualBox:/tmp$ ./t1.sh
请输入密码:123
请再次输入密码:345
密码不一致,请重试
case分支
case $1 in
start | begin)
echo "I am started!"
;;
stop | end)
echo "I am stopped!"
;;
*)
echo "Other command!"
;;
esac
#!/bin/bash
case $1 in
[1-4]) echo "这是1-4"
;;
[5-8]) echo "这是5-8"
;;
[9-10]) echo "这是9-10"
;;
esac
网友评论