Shell编程基础

题目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



  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值