标签:style blog class code java color
练习题(这里贴的是自己写的代码, 网上给的题目代码我会附加在最下面)
1. 编写shell脚本,计算1-100的和;
1 #!/bin/bash 2 #caculate the sum of numbers from 1 to 100 3 4 sum=0 5 for i in `seq 1 100`; do 6 sum=$[$sum+$i] 7 done 8 echo $sum
2. 编写shell脚本,要求输入一个数字,然后计算出从1到输入数字的和,要求,如果输入的数字小于1,则重新输入,直到输入正确的数字为止;
1 #!/bin/bash 2 3 read -p "please input a positive interger: " x 4 while [ $x -lt 1 ]; do 5 read -p "please input a positive interger: " x 6 done 7 8 sum=0 9 for i in `seq 1 $x`; do 10 sum=$[$sum+$i] 11 done 12 echo $sum
3. 编写shell脚本,把/root/目录下的所有目录(只需要一级)拷贝到/tmp/目录下;
(注: 执行程序时需root)
1 #!/bin/bash 2 3 for dir in `ls /root/`; do 4 if [ -d $dir ]; then 5 cp -r $dir /tmp/ 6 fi 7 done
4. 编写shell脚本,批量建立用户user_00, user_01, … ,user_100并且所有用户同属于users组;
groupadd,groupdel, useradd, userdel 这类命令几乎没使用过,额好吧,不要给自己找理由。
1 #! /bin/bash 2 3 groupadd users 4 5 for i in `seq 0 9`; do 6 7 useradd -g users user_0$i 8 9 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)。
暂时还是不会做
1 以下为练习题答案: 2 3 1. #! /bin/bash 4 5 sum=0 6 7 for i in `seq 1 100`; do 8 9 sum=$[$i+$sum] 10 11 done 12 13 echo $sum 14 15 2. #! /bin/bash 16 17 n=0 18 19 while [ $n -lt "1" ]; do 20 21 read -p "Please input a number, it must greater than "1":" n 22 23 done 24 25 26 27 sum=0 28 29 for i in `seq 1 $n`; do 30 31 sum=$[$i+$sum] 32 33 done 34 35 echo $sum 36 37 38 39 3. #! /bin/bash 40 41 for f in `ls /root/`; do 42 43 if [ -d $f ] ; then 44 45 cp -r $f /tmp/ 46 47 fi 48 49 done 50 51 52 53 4. #! /bin/bash 54 55 groupadd users 56 57 for i in `seq 0 9`; do 58 59 useradd -g users user_0$i 60 61 done 62 63 64 65 for j in `seq 10 100`; do 66 67 useradd -g users user_$j 68 69 done 70 71 72 73 5. #! /bin/bash 74 75 awk -F‘:‘ ‘$0~/abc/ {print $1}‘ test.log >/tmp/n.txt 76 77 sort -n n.txt |uniq -c |sort -n >/tmp/n2.txt 78 79 awk ‘$1>10 {print $2}‘ /tmp/n2.txt 80 81 82 83 6. #! /bin/bash 84 85 checkip() { 86 87 if echo $1 |egrep -q ‘^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$‘ ; then 88 89 a=`echo $1 | awk -F. ‘{print $1}‘` 90 91 b=`echo $1 | awk -F. ‘{print $2}‘` 92 93 c=`echo $1 | awk -F. ‘{print $3}‘` 94 95 d=`echo $1 | awk -F. ‘{print $4}‘` 96 97 98 99 for n in $a $b $c $d; do 100 101 if [ $n -ge 255 ] || [ $n -le 0 ]; then 102 103 echo "the number of the IP should less than 255 and greate than 0" 104 105 return 2 106 107 fi 108 109 done 110 111 else 112 113 echo "The IP you input is something wrong, the format is like 192.168.100.1" 114 115 return 1 116 117 fi 118 119 } 120 121 122 123 rs=1 124 125 while [ $rs -gt 0 ]; do 126 127 read -p "Please input the ip:" ip 128 129 checkip $ip 130 131 rs=`echo $?` 132 133 done 134 135 echo "The IP is right!"
shell脚本练习题(更新中...),布布扣,bubuko.com
标签:style blog class code java color
原文地址:http://www.cnblogs.com/Stomach-ache/p/3709754.html