习题1:用户交互脚本

要求:写一个脚本,执行后,打印一行提示“Please input a number:”,要求用户输入数值,然后打印出该数值,然后再次要求用户输入数值。直到用户输入”end”停止。

参考答案:

#!/bin/bash
# date:2018年3月5日
while :
do
 read -p "Please input a number:(end for exit) " n
 num=` echo $n |sed -r 's/[0-9]//g'|wc -c `
 if [ $n == "end" ]
 then
     exit
 elif [ $num -ne 1 ]
 then
     echo "Please input a number。"
 else
     echo "$n"
 fi
done

习题2:脚本传参

要求:使用传参的方法写个脚本,实现加减乘除的功能。例如:  sh  a.sh  1   2,这样会分别计算加、减、乘、除的结果。

    1 脚本需判断提供的两个数字必须为整数

    2 当做减法或者除法时,需要判断哪个数字大

    3 减法时需要用大的数字减小的数字

    4 除法时需要用大的数字除以小的数字,并且结果需要保留两个小数点。

参考答案:

#/bin/bash
# date: 2018年3月5日
if [ $# -ne 2 ];then
    echo "Please Usage: ./$0 num1 num2."
    exit 1
fi
is_int(){
    if echo "$1"|grep -q [^0-9];then
        echo "$1 is not a number."
        exit 1
    fi
}
max(){
    if [ $1 -ge $2 ];then
        echo $1
    else
        echo $2
    fi
}
min(){        
    if [ $1 -lt $2 ];then
        echo $1
    else
        echo $2
    fi
}
sum(){
    echo "$1 + $2 = $[$1+$2]"
}
sub(){
    large=`max $1 $2`
    small=`min $1 $2`
    echo "$large - $small = $[$large-$small]"
}
mul(){
    echo "$1 * $2 = $[$1*$2]"
}
div(){
    large=`max $1 $2`
    small=`min $1 $2`
    d=`echo "scale=2; $large / $small"|bc`
    echo "$large / $small = $d"
}
is_int $1
is_int $2
sum $1 $2
sub $1 $2
mul $1 $2
div $1 $2

习题3:被3整除

要求:写一个脚本: 计算100以内所有能被3整除的正整数的和

参考答案:

#/bin/bash
# date: 2018年3月5日
sum=0
for i in `seq 1 100`
do
    if[ $[$i%3] -eq 0 ];then
        sum=$[$sum+$i]
    fi
done
echo "sum=$sum"