[2018.07.23 learning notes] [linux advanced knowledge Shell script programming exercise]

1. Write shell script to calculate the sum of 1-100;

#!/bin/bash
sum=0
for i in `seq 1 100`
do
  sum=$[$sum+$i]
done
echo $sum

2. Write a shell script, ask to input a number, and then calculate the sum from 1 to the input number. If the input number is less than 1, input again until the correct number is input;

#!/bin/bash
n=0
while [ $n -lt "1" ]
do
  read -p "Please input a number: " n
done

sum=0
for i in `seq 1 $n`
do
  sum=$[$sum+$i]
done
echo $sum

3. Write shell script, copy all directories (only one level) under / root / directory to / tmp / directory;

#!/bin/bash
cd /root/

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

4. Write a shell script, and batch create the user "user 00, user" 01,... User "100. All users belong to the users group;

#!/bin/bash

groupadd users

for i in `seq 0 9`
do 

   useradd -g users user_0$i
done

for j in `seq 10 100`
do
   useradd -g users user_$j
done

5. Write a shell script to intercept the first column in the row containing the keyword "abc" in the file test.log (assuming the separator is "). Then sort the intercepted numbers (assuming the first column is a number), and print out the columns with more than 10 repetitions;

#!/bin/bash

grep 'abc' test.log|awk -F ':' {print $1}|sort -n|uniq -c|sort -n|awk '$1 >10 {print $2}'

6. Write a shell script to determine whether the input IP is correct (the rule of IP is n1.n2.n3.n4, in which 1 < N1 < 255, 0 < N2 < 255, 0 < N3 < 255, 0 < N4 < 255).

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!"

Keywords: shell less

Added by krraleigh on Fri, 31 Jan 2020 16:17:42 +0200