Shell编程基础

来源:互联网 发布:stm32jlink 烧录软件 编辑:程序博客网 时间:2024/06/05 15:45

题目1:猜数字,输入一个数,判断是否与程序中的数相同。

<span style="font-family:Arial;font-size:12px;">#!/bin/bashsecret=$RANDOMsecret=`expr $secret % 10`i=1while [ $i -le 3 ]doecho "Guess the number between 0 and 9:"read numif [ $num -eq $secret ]thenecho "Bingo"; exitelseecho "Sorry, u r wrong."echo "You still have `expr 3 - $i` chance(s)."i=`expr $i + 1`fidoneecho "GAME OVER"</span>


题目2:输入用户名、密码,如果正确登录,不正确报错。

<span style="font-family:Arial;font-size:12px;">#!/bin/bashecho "welcome to ubuntu, please input your username and password."for ((i=0;i<3;i++))doread -p "username:" usernameread -p "password:" -s passwdif [ $username = "user" -a $passwd = "123"]; thenecho "login success"breakelseecho "username or password error, please try again"fidoneif [ $i -eq 3 ]; thenecho "Sorry, you cannot login."fi</span>


题目3:输入几位同学的成绩,计算平均成绩。

<span style="font-family:Arial;font-size:12px;">#!/bin/bashdeclare -i n=5declare -i sum=0echo "input five students' scores:"for i in `seq $n`doread scoresum=`expr $sum + $score`doneecho "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



0 0
原创粉丝点击