每天一道编程题(3)

1. 编写一个shell脚本,从键盘读入10个数,显示最大值和最小值。

#!/bin/sh
echo "Enter your number:"
read input
max="$input"
min="$input"
for i in $(seq 2 10)
do
        read a
        if [ `echo $a| awk -v b=$max '{ print($1>b)?"1":"0"}'` -eq "1" ]; then
                max="$a"
        elif [ `echo $a| awk -v c=$min '{ print($1<c)?"1":"0"}'` -eq "1" ]; then
                min="$a"
        fi
done
echo "Max is $max"
echo "Min is $min"

    这么小小一段shell,竟然调试了两小时,shell的if忘掉了,判断忘掉了,读入输入也忘掉了。再来巩固一下吧。

   1) if语句:

if  条件
then
 Command
elif;then
 Command
else
 Command
fi 

    切记shell每句结束可以不用分号,冒号,如果加入分号,表示为两句,故也可以写成这种样式:if 条件;then;

   2)条件语句:

    if的条件可以表示为[ expression ],切记shell中括号与符号之间留空,不然系统无法识别。expression可以表示如下:

if [ $a == $b ] ; then   // a=b // 
if [ $a -gt $b ]; then  // a>b
if [ $a -lt $b ]; then   // a<b
if [ $a -eq $b ]; then // a =b
if [ $a -ge $b ]; then // a>=b
if [ $a -le $b ]; then // a <=b

    if也可以和test 结合,所以上面也可表示为:

if  test $a -eq $b ; then
if  test $a -gt $b ; then
if  test $a -lt $b ; then

    写为一行即:if test $a -lt $b; then echo "Hell";  else echo "PP"; fi 

   3)注意shell首次赋值时,不需要$,凡有$变量名的地方,即指其值,否则shell表示不认识;

   4) for循环的语句为:

for x in one two three four
do
        echo number $x
done

   

for x in /home/w/share/*
do
        echo $(basename $x) is a file 
done

    表示为一行即:

for  x in /home/w/share/*; do echo $x is a file; done 

    序列为位置参数:

for thing in "$@"
do
        echo you typed ${thing}.
done

    遍历自增序列也可以为:

   

for (( i=1; i<=5; i++ ))
do
        echo "i=$i"
done

   5) 顺便看看while循环:

   

myvar=1
while [ $myvar -le 10 ]
do
        echo $myvar
        myvar=$(( $myvar + 1 ))
done

    注意myvar=$(( $myvar + 1 )),赋值时不能加$,不然即为1=1+2;而且myvar与=之间不能有空格,否则shell无法识别此为赋值。这句也可以表示为myvar=`expr $myvar + 1`。

 变量自增有以下几种方式:

  • i=`expr $i + 1`//expr $i + 1中间需有空格,不然不认
  • let i+=1     //i+=1中间不能有空格,否则shell不认
  • ((i++))   // 可以有空格可以无
  • i=$(($i+1)) //可有空格也可无

     最后,看看别人写的:

#!/bin/sh
read -p 'Please enter 10 numbers: ' numbers
awk '{max=min=$1;for(i=1;i++<NF;){if($i>max)max=$i;if($i<min)min=$i}printf "max: %d, min: %d\n",max,min}' <<< $numbers

猜你喜欢

转载自yeluowuhen.iteye.com/blog/2274321