shell练习题
1.计算从1到100所有整数的和
#!/bin/bash
he=0
for y in {1..100}
do
he=$[$y+$he]
done
echo "1~100整数总和为$he "
结果
[root@localhost opt]# ./yyy1.sh
1~100整数总和为5050
2.提示用户输入一个小于100的整数,并计算从1到该数之间所有整数的和
for方法
#!/bin/bash
read -p "请输入小于100的整数: " zs
he=0
for ((y=1; y<=zs; y++))
do
he=$[$he+$y]
done
echo "从1到$zs的整数和为: $he "
结果
[root@localhost opt]# ./yyy2.sh
请输入小于100的整数: 3
从1到3的整数和为: 6
while方法
#!/bin/bash
#1到100的整数
read -p "请输入大于0且小于100的整数" num
sum=0;i=0
while [ $i -lt $num ]
do
let "i=$i+1";let "sum=$sum+$i"
done
echo "1到100的整数和为$sum"
3.求从1到100所有整数的偶数和、奇数和
其中奇数的单算
#!/bin/bash
os=0
for y in {1..100..2}
do
os=$[$y+$os]
done
echo "奇数和为:$os "
结果
[root@localhost opt]# ./yyy3.sh
奇数和为:2500
奇数偶数一块算
#!/bin/bash
os=0
for y in {1..100..2}
do
os=$[$y+$os]
done
echo "奇数和为:$os "
ous=0
for p in {0..100..2}
do
ous=$[$p+$ous]
done
echo "偶数和为:$ous "
结果
[root@localhost opt]# ./yyy3.sh
奇数和为:2500
偶数和为:2550
4.写个逛淘宝选购商品脚本,每家商店有五种商品选购(衣服500元,裤子400元,鞋子350元,帽子150元,袜子50元),每次选购完或不买都会提示用户是否继续逛下一家商店,如果不再继续逛的话进行购物车结算总额。
#!/bin/bash
i=1
sum=0
while true
do
echo "来到第$i家店门口"
read -p "请问是否需要进行购物?yes/no " gw
while [ $gw = "yes" ]
do
echo "1.衣服500元"
echo "2.裤子400元"
echo "3.鞋子350元"
echo "4.帽子150元"
echo "5.袜子50元"
echo "放弃购物"
read -p "请问您要购买哪些商品呢亲,请输入号码哦" hm
case $hm in
1)
let ypy+=500
echo "成功消费$ypy元 "
;;
2)
let ypy+=400
echo "成功消费$ypy元 "
;;
3)
let ypy+=350
echo "成功消费$ypy元 "
;;
4)
let ypy+=150
echo "成功消费$ypy元 "
;;
5)
let ypy+=50
echo "成功消费$ypy元 "
;;
*)
echo " 放弃 "
break
esac
read -p "请问是继续购物还是结算购物车? yes/no " zc
done
read -p "是否继续购物 yes/no " do
if [ $do = "yes" ]
then
let i++
else
break
fi
done
echo -e "一共经过$i家店. \n合计购物总价:$ypy "