想要提升shell脚本能力,练习必不可少。真正有效的练习方法之一就是穷举法。
所谓的穷举法,就是把一个脚本练到极致。
任何脚本都讲究循序渐进,先从最简单的功能开始,逐渐增加难度。在同一个难度的级别,用多种方法反复穷举。
比如这个初级难度级别:
写一个购物清单脚本,列出4个商品供用户选择,用户选中就提示已被选中。提示完成,继续进入下一轮的选择。
第一阶段,从最初级的脚本开始练起:
方法一:
#!/bin/bash
while true
do
### 使用函数,输出4个选项
list(){
cat <<END
1.apple
2.banana
3.pear
4.orange
please slect one that you like:
END
}
list
read num
if [ $num -eq 1 ];then
echo "this is an apple"
elif [ $num -eq 2 ];then
echo "this is an banana"
elif [ $num -eq 3 ];then
echo "this is a pear"
elif [ $num -eq 4 ];then
echo "this is an orange"
else
echo "please retry!"
fi
done
方法二:
[root@laoxin22 ~]# cat list.sh
#!/bin/bash
list(){
cat <<END
1.apple
2.banana
3.pear
4.orange
please slect one that you like:
END
}
num(){
read num
if [ $num -eq 1 ];then
echo "this is an apple"
elif [ $num -eq 2 ];then
echo "this is an banana"
elif [ $num -eq 3 ];then
echo "this is a pear"
elif [ $num -eq 4 ];then
echo "this is an orange"
else
echo "please retry!"
fi
}
while true
do
list
num
echo "#########begin##############"
done
方法三:
#!/bin/bash
list(){
cat << EOF
1.apple
2.banana
3.pear
4.orange
please select one that you like:
EOF
}
list
for (( ; ; ))
do
num1=1
num2=2
num3=3
num4=4
read NUM
if [ $NUM == $num1 ];then
echo "you chose is apple!"
elif [ $NUM == $num2 ];then
echo "you chose is banana!"
elif [ $NUM == $num3 ];then
echo "you chose is pear!"
elif [ $NUM == $num4 ];then
echo "you chose is orange!"
else
echo "you should select right num!"
exit
fi
done
这里只举了三个方法,在练习的时候还可以继续尝试更多方法,在同一个难度级别反复穷举。
穷举最大的好处就是让你通过一个脚本,练习了不同的shell脚本语法。
当练习完同一级别后,就可以增加脚本功能, 比如在当前的基础上,在增加判断用户输入的是否为数字,增加订单的创建等等。
分享一: 生产环境必备shell脚本