题目1:猜数字,输入一个数,判断是否与程序中的数相同。
<span style="font-family:Arial;font-size:12px;">#!/bin/bash
secret=$RANDOM
secret=`expr $secret % 10`
i=1
while [ $i -le 3 ]
do
echo "Guess the number between 0 and 9:"
read num
if [ $num -eq $secret ]
then
echo "Bingo"; exit
else
echo "Sorry, u r wrong."
echo "You still have `expr 3 - $i` chance(s)."
i=`expr $i + 1`
fi
done
echo "GAME OVER"</span>
题目2:输入用户名、密码,如果正确登录,不正确报错。
<span style="font-family:Arial;font-size:12px;">#!/bin/bash
echo "welcome to ubuntu, please input your username and password."
for ((i=0;i<3;i++))
do
read -p "username:" username
read -p "password:" -s passwd
if [ $username = "user" -a $passwd = "123"]; then
echo "login success"
break
else
echo "username or password error, please try again"
fi
done
if [ $i -eq 3 ]; then
echo "Sorry, you cannot login."
fi</span>
题目3:输入几位同学的成绩,计算平均成绩。
<span style="font-family:Arial;font-size:12px;">#!/bin/bash
declare -i n=5
declare -i sum=0
echo "input five students' scores:"
for i in `seq $n`
do
read score
sum=`expr $sum + $score`
done
echo "The total is $sum."
ave=`expr $sum / $n`
echo "The average is $ave."</span>
注意:
执行shell程序时,可采用两种方法:
方法1:bash xxx.sh
方法2:chmod a+x xxx.sh (如果不加权限不能执行)
./xxx.sh