shell練習題20180723

  1. 編寫shell腳本,計算1-100的和;
    [root@yong-01 20180723]# vim sum100.sh
    
    #!/bin/bash
    sum=0
    for i in `seq 1 100`
    do
       sum=$[$sum+$i]
    done
    echo $sum

     

  2. 編寫shell腳本,要求輸入一個數字,而後計算出從1到輸入數字的和,要求,若是輸入的數字小於1,則從新輸入,直到輸入正確的數字爲止;
    [root@yong-01 20180723]# vim he_n.sh
    
    #!/bin/bash
    n=0
    while [ $n -le "1" ]
    do read -p "Please in put a nubmer,it must greater than "1": " n
    done
    sum=0
    for i in `seq 1 $n`
    do
      sum=$[$sum+$i]
    done
    echo $sum

     

  3. 編寫shell腳本,把/root/目錄下的全部目錄(只須要一級)拷貝到/tmp/目錄下;
    [root@yong-01 20180723]# vim cp_root.sh 
    
    #!/bin/bash
    cd /root
    for f in `ls`;do
        if [ -d $f ];then
            cp -r $f /tmp/
        fi
    done

     

  4. 編寫shell腳本,批量創建用戶user_00, user_01, ... user_100而且全部用戶同屬於users組;
    [root@yong-01 20180723]# vim useradd.sh
    
    #!/bin/bash
    groupadd users
    for i in `seq -w 1 100|sed "s/^0//g"`
    do
       useradd -g users user_$i
    done

     

  5. 編寫shell腳本,截取文件test.log中包含關鍵詞 ‘abc’ 的行中的第一列(假設分隔符爲 」:」 ),而後把截取的數字排序(假設第一列爲數字),而後打印出重複次數超過10次的列;
    [root@yong-01 20180723]# vim test.sh
    
    #! /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

     

  6. 編寫shell腳本,判斷輸入的IP是否正確(IP的規則是,n1.n2.n3.n4,其中1<n1<255, 0<n2<255, 0<n3<255, 0<n4<255)。
    [root@yong-01 20180723]# vim check_ip.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 number of the IP should less than 255 and greate than 0"
                                    return 2
                            fi
                    done
            else
    
                    echo "The IP you input is something wrong, the format is like 192.168.100.1"
                    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!"
相關文章
相關標籤/搜索