第十二章:shell脚本课后习题

第十二章:shell脚本课后习题

1.编写shell脚本,计算1~100的和。

[root@zl_cloud sbin]# cat 1.sh
#! /bin/bash

sum=0
for i in `seq 1 100`;do
        sum=$[$i+$sum]
done
echo $sum
[root@zl_cloud sbin]#

2.编写shell脚本,输入一个数字n并计算1~n的和。要求:如果输入的数字小于1,则重新输入,直到输入正确的数字为止。

正确答案:

[root@zl_cloud sbin]# vi 2.sh
#! /bin/bash

read -p "please input a num:" n
while ((n<1));do
        read -p "输入数字小于1,请重新输入:" n
done

for i in `seq 1 $n`;do
        sum=$[$i+$n]
done
echo $sum
[root@zl_cloud sbin]#

这是我第一次尝试的用if语句(后面发现是错的):

#! /bin/bash

read -p "please input a num:" n
if ((n<1));then
        read -p "输入数字小于1,请重新输入:" n
else
        for i in `seq 1 $n`;do
                sum=$[$i+$n]
        done
        echo $sum
fi

发现大于等于1时是可以计算的,但是到了小于1的数字时,它只会说重新输入,输入完就直接退出这个脚本了,于是我又尝试了:

#! /bin/bash

read -p "please input a num:" n
if ((n<1));then
        read -p "输入数字小于1,请重新输入:" n
        for i in `seq 1 $n`;do
                sum=$[$i+$n]
        done
        echo $sum
else
        for i in `seq 1 $n`;do
                sum=$[$i+$n]
        done
        echo $sum
fi

然后我又试了一下小于1的部分,它提醒我重新输入,重新输入后它会空一行,然后退出脚本。(可能是直接输出了$sum,但是for没有计算。最后我就换了while语句,得到答案)

3.编写shell脚本,把/root/目录下的所有目录(只需要一级)复制到/tmp/目录下。

[root@zl_cloud sbin]# vi 3.sh
#! /bin/bash

cd /root/
for f in `ls`;do
        if [ -d $f ];then
                cp -r $f /tmp/
        fi
done
[root@zl_cloud sbin]#

4.编写shell脚本,批量建立用户user_OO, user_01… user_99。要求:所有用户同属于users组。

[root@zl_cloud sbin]# vi 4.sh
#! /bin/bash

groupadd users
for i in `seq -w 0 99`;do
        useradd -g users user_o$i'
done
[root@zl_cloud sbin]#

5.编写shell脚本,截取文件test.log中包含关键词abc的行中的第1列(假设分隔符为:),然后把截取的数字排序(假设第1列为数字),最后打印出重复超过10次的列。

[root@zl_cloud sbin]# vi 5.sh
#! /bin/bash

touch /root/shell.txt
touch /root/shell1.txt
awk -F ':' '$0~/abc/ {print $1}' /root/test.log > /root/shell.txt
sort -n /root/shell.txt |uniq -c |sort -n > /root/shell1.txt
awk '$1>10 {print $2}' /root/shell1.txt
[root@zl_cloud sbin]#

6.编写shell脚本,判断输入的IP是否正确。要求:IP的规则是n1.n2.n3.n4,其中1<n1<255.0<n2<255, 0<n3<255. 0<n4< 255)。

[root@zl_cloud sbin]# vi 6.sh
#! /bin/bash

checkip()
{
    if echo $1 |egrep -q '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$'
    then
        a=`echo $1 | awk -F '.' '{print $1}'`
        b=`echo $1 | awk -F '.' '{print $2}'`
        c=`echo $1 | awk -F '.' '{print $3}'`
        d=`echo $1 | awk -F '.' '{print $4}'`

        for n in $a $b $c $d;do
                if [ $n -ge 255 ] || [ $n -le 0 ];then
                     echo "the num should less than 255 and greate than 0"
                     return 2
                fi
                done
                else
                    echo "the IP is wrong,the format is like 192.168.10.129"
                    return 1
                fi
}               

rs=1
while [ $rs -gt 0 ];do
        read -p "please input the ip:" ip
        checkip $ip
        rs=`echo $?`
done
echo "The IP is right"
[root@zl_cloud sbin]#

猜你喜欢

转载自blog.csdn.net/zhang_ZERO/article/details/105151996