想要提升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 ~]#