练习题(这里贴的是自己写的代码, 网上给的题目代码我会附加在最下面)

1. 编写shell脚本,计算1-100的和;

 #!/bin/bash
#caculate the sum of numbers from to sum=
for i in `seq `; do
sum=$[$sum+$i]
done
echo $sum

2. 编写shell脚本,要求输入一个数字,然后计算出从1到输入数字的和,要求,如果输入的数字小于1,则重新输入,直到输入正确的数字为止;

 #!/bin/bash

 read -p "please input a positive interger: " x
while [ $x -lt ]; do
read -p "please input a positive interger: " x
done sum=
for i in `seq $x`; do
sum=$[$sum+$i]
done
echo $sum

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

(注: 执行程序时需root)

 #!/bin/bash

 for dir in `ls /root/`; do
if [ -d $dir ]; then
cp -r $dir /tmp/
fi
done

4. 编写shell脚本,批量建立用户user_00, user_01, … ,user_100并且所有用户同属于users组;

groupadd,groupdel, useradd, userdel 这类命令几乎没使用过,额好吧,不要给自己找理由。

  #! /bin/bash

 groupadd users

 for i in `seq  `; do

     useradd -g users user_0$i

 done

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

暂时不会做 :(.....需要学习awk以及sort命令的使用

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

暂时还是不会做

 以下为练习题答案:

 . #! /bin/bash

 sum=

 for i in `seq  `; do

 sum=$[$i+$sum]

 done

 echo $sum

 . #! /bin/bash

 n=

 while [ $n -lt "" ]; do

 read -p "Please input a number, it must greater than "":" n

 done

 sum=

 for i in `seq  $n`; do

 sum=$[$i+$sum]

 done

 echo $sum

 . #! /bin/bash

 for f in `ls /root/`; do

 if [ -d $f ] ; then

 cp -r $f /tmp/

 fi

 done

 . #! /bin/bash

 groupadd users

 for i in `seq  `; do

 useradd -g users user_0$i

 done

 for j in `seq  `; do

 useradd -g users user_$j

 done

 . #! /bin/bash

 awk -F':' '$0~/abc/ {print $1}' test.log >/tmp/n.txt

 sort -n n.txt |uniq -c |sort -n >/tmp/n2.txt

 awk '$1>10 {print $2}' /tmp/n2.txt

 . #! /bin/bash

 checkip() {

 if echo $ |egrep -q '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$' ; then

 a=`echo $ | awk -F. '{print $1}'`

 b=`echo $ | awk -F. '{print $2}'`

 c=`echo $ | awk -F. '{print $3}'`

 d=`echo $ | awk -F. '{print $4}'`

 for n in $a $b $c $d; do

 if [ $n -ge  ] || [ $n -le  ]; then

 echo "the number of the IP should less than 255 and greate than 0"

 return

 fi

 done

 else

 echo "The IP you input is something wrong, the format is like 192.168.100.1"

 return

 fi

 }

 rs=

 while [ $rs -gt  ]; do

 read -p "Please input the ip:" ip

 checkip $ip

 rs=`echo $?`

 done

 echo "The IP is right!"
05-17 18:31