这篇文章主要介绍shell编程的实例
一、逻辑判断之if语句
1.判断年龄?
[root@centos7 9_1 ]#cat iftest.sh
#!/bin/bash
read -p "Please input your age:" age
## 判断用户输入的必须是数字
if [[ "$age" =~ ^[0-9]+$ ]];then
true
else
echo "Please input digit"
exit 10
fi
## 判断用户的年龄,并输出相应的信息
if [ "$age" -ge 0 -a $age -le 18 ];then
echo "good good study,day day up"
elif [ "$age" -gt 18 -a $age -le 60 ];then
## 由于前面已经判断为数字,并且为正整数,所以的 "$age" -gt 18 可以省略;
echo "work hard"
elif [ "$age" -gt 60 -a $age -le 120 ];then
## 同理,这里的"$age" -gt 60也可以省略,优化
echo "enjoy your life"
else
echo "you don not come from the earch"
fi
2.如何判断yes或no?
思路1:
1.用户输入的所有选择:y|yes|Y|YES,同n|no|N|NO
2.统一判断为大写或者小写:tr进行转换
3.使用两种选择判断:2:使用正则匹配y|yes;n|no或者大写
#!/bin/bash
read -p "Input yes or no:" answer
ans=`echo "$answer"|tr 'A-Z' 'a-z'`
if [ "$ans" = "yes" -o "$ans" = "y" ];then
echo "YES"
elif [ "$ans" = "no" -o "$ans" = "n" ];then
echo "NO"
else
echo "Please input yes or no"
fi
思路2:使用正则进行判断
#!/bin/bash
read -p "Input yes or no:" answer
if [[ "$answer" =~ ^[Yy]([Ee][Ss])?$ ]];then
echo YES
elif [[ "$answer" =~ ^[Nn][Oo]?$ ]];then
echo "NO"
else
echo "Please input yes or no"
fi
4.判断是否富有或帅气?
[root@centos7 9_1 ]#vim yesorno2.sh
#!/bin/bash
read -p "Are you rich? yes or no: " answer
if [[ "$answer" =~ ^[Yy]([Ee][Ss])?$ ]];then
echo OK
elif [[ "$answer" =~ ^[Nn][Oo]?$ ]];then
read -p "Are you handsome? yes or no: " answer
if [[ "$answer" =~ ^[Yy]([Ee][Ss])?$ ]];then
echo Ok
exit
elif [[ "$answer" =~ ^[Nn][Oo]?$ ]];then
echo "work hard"
else
echo "Please input yes or no"
fi
else
echo "Please input yes or no"
fi
二、逻辑判断之case语句
1.判断数字
[root@centos7 9_1 ]#vim casetest.sh
#!/bin/bash
read -p "Please input a digit: " num
case $num in
1|2|3)
echo 1,2,3
;;
4|5|6)
echo 4,5,6
;;
7|8|9)
echo 7,8,9
;;
*)
echo other digit
;;
esac
2.判断yes|no
#!/bin/bash
read -p "Please input yes or no: " ans
case $ans in
[Yy]|[Yy][Ee][Ss])
echo YES
;;
[Nn]|[Nn][Oo])
echo NO
;;
*)
echo input false
;;
esac
3.打印菜单:
[root@CentOS6 ~ ]#cat menu.sh
#!/bin/bash
cat <
1:lamian
2:huimian
3:daoxiaomian
4:junbing
5:mifan
EOF
read -p "Please choose the number: " num
case $num in
1)
echo "lamian price is 15"
;;
2)
echo "huimian price is 18"
;;
3)
echo "daoxiaomian price is 13"
;;
4)
echo "junbing price is 10"
;;
5)
echo "mifan price is 2"
;;
*)
echo "INPUT false"
esac
效果:
[root@CentOS6 ~ ]#sh menu.sh
1:lamian
2:huimian
3:daoxiaomian
4:junbing
5:mifan
Please choose the number: 5
mifan price is 2
三、循环之for循环
help for————两种语法
语法1:
for NAME [in WORDS ... ] ; do COMMANDS; done
语法2:
for ((: for (( exp1; exp2; exp3 )); do