练习8

作者: Stone_説 | 来源:发表于2020-04-11 23:13 被阅读0次

    1.每隔3秒到系统上获取已经登录的用户的信息;如果发现用户hacker登录,则将登录时间和主机记录于日志/var/log/login.log中,并退出脚本

    #!/bin/bash
    >/var/log/login.log
    until false;do
       if who |grep "^hacker\>" &>/dev/null;then
         who|grep "^hacker\>">/var/log/login.log
             break
       fi
               sleep 3
    done
    

    2.随机生成10以内的数字,实现猜字游戏,提示比较大小,相等则退出

    [root@centos7 ~]# vim test8.sh 
    #!/bin/bash
    read -p "please input compare num:" com_num
    set ran_num
    ran_num=$[$RANDOM%10]
    echo $ran_num
    echo $com_num
    [ $ran_num -eq $com_num ] && echo "equal" && exit 11
    [ $ran_num -le $com_num ] && echo "less than" && exit 12
    [ $ran_num -gt $com_num ] && echo "big than" && exit 13
    

    3.用文件名做为参数,统计所有参数文件的总行数

    [root@centos7 ~]# cat test9.sh 
    #!/bin/bash
    [ -a $1 ]||{ echo "the file is not exist,please input again";exit 10; }
    [ $# -eq 0 ]&& echo "you must input a filename"&& exit 100
    let sum=0
    until [ $# -eq 0 ];do
            n=`wc -l<$1`&>/dev/null
            let sum+=n
            shift
    done
    echo sum=$sum
    [root@centos7 ~]# ./test9.sh /etc/passwd test8.sh
    sum=54
    

    4.用两个以上的数字为参数,显示其中的最大值和最小值

    [root@centos7 ~]# cat test10.sh 
    #!/bin/bash
    if [ $# -lt 2 ];then
            echo "please input at least two numbers"
            exit 11
    fi
    
    declare -i max_num
    declare -i min_num
    declare -i num=$#
    until [ $# = 0 ];do
            if [[ ! "$1" =~ ^[0-9]+$ ]];then 
                    echo wrong number $1
                    exit
            fi
            if [ $num = $# ];then
                    let max_num=$1
                    let min_num=$1
            else 
                    if [ $1 -gt $max_num ];then
                            let max_num=$1
                    elif [ $1 -lt $min_num ];then
                            let min_num=$1
                    fi
            fi
            shift
    done
    echo max=$max_num
    echo min=$min_num
    [root@centos7 ~]# ./test10.sh 123 132 43 45 89
    max=132
    min=43
    

    相关文章

      网友评论

          本文标题:练习8

          本文链接:https://www.haomeiwen.com/subject/qzljkhtx.html