【shell】shell条件测试

shell条件测试

1.测试格式

test 条件表达式,或者[ 条件表达式 ] ,或者 [[ 条件表达式 ]],其实我们可以man test查看一下用法

TEST(1)                          User Commands                         TEST(1)

NAME
       test - check file types and compare values

SYNOPSIS
       test EXPRESSION
       test

       [ EXPRESSION ]
       [ ]
       [ OPTION

2.表达格式

可以按照man test里面的格式要求

( EXPRESSION )
              EXPRESSION is true
! EXPRESSION
              EXPRESSION is false
EXPRESSION1 -a EXPRESSION2
              both EXPRESSION1 and EXPRESSION2 are true
EXPRESSION1 -o EXPRESSION2
              either EXPRESSION1 or EXPRESSION2 is true

这里的a可以记忆为and,o可以记为or,比较直接

3.文件操作

文件操作,同样还是截取man test里面的参数选择

-b FILE
           FILE exists and is block special
-c FILE
              FILE exists and is character special
-d FILE
              FILE exists and is a directory
-e FILE
              FILE exists
-f FILE
              FILE exists and is a regular file
-g FILE
              FILE exists and is set-group-ID
-G FILE
              FILE exists and is owned by the effective group ID
-h FILE
              FILE exists and is a symbolic link (same as -L)
-k FILE
              FILE exists and has its sticky bit set
-L FILE
              FILE exists and is a symbolic link (same as -h)
-O FILE
              FILE exists and is owned by the effective user ID
-p FILE
              FILE exists and is a named pipe
-r FILE
              FILE exists and read permission is granted
-s FILE
              FILE exists and has a size greater than zero
-S FILE
              FILE exists and is a socket
-t FD  file descriptor FD is opened on a terminal
-u FILE
              FILE exists and its set-user-ID bit is set
-w FILE
              FILE exists and write permission is granted
-x FILE
              FILE exists and execute (or search) permission is granted

实例

3.1 创建备份文件

创建备份文件,首先判断文件是否存在,文件不存在则创建,开始备份

[klaus@localhost chapt3]$ ls
test_mysqlback.sh
[klaus@localhost chapt3]$ cat test_mysqlback.sh
#!/bin/bash
back_dir=/home/klaus/Desktop/shell/chapt3/mysqlback
# if ! test -d $back_dir;then
if [ ! -d $back_dir ];then
    mkdir -p $back_dir
fi

echo "start backup..."
[klaus@localhost chapt3]$ ./test_mysqlback.sh
start backup...
[klaus@localhost chapt3]$ ls
mysqlback  test_mysqlback.sh

这里用到-d,即判断back_dir是不是一个目录文件

3.2 创建用户

创建用户可以用到id user来查看用户是否存在,主要逻辑是首先判断用户是否存在,不存在则创建

[klaus@localhost chapt3]$ sudo userdel -r alice
[klaus@localhost chapt3]$ id alice
id: alice: No such user
[klaus@localhost chapt3]$ cat usradd.sh
#!/bin/bash
read -p "please input a username:" user

if id $user &>/dev/null;then
    echo "user $user already exists!"
    exit
else
    sudo useradd $user
    if [ $? -eq 0 ];then
        echo "User $user created successfully!"

    fi
fi
[klaus@localhost chapt3]$ ./usradd.sh
please input a username:alice
User alice created successfully!
[klaus@localhost chapt3]$ id alice
uid=502(alice) gid=502(alice) groups=502(alice)
[klaus@localhost chapt3]$ ./usradd.sh
please input a username:alice
user alice already exists

4.数值比较

同样还是截取man test里面的用法

INTEGER1 -eq INTEGER2
              INTEGER1 is equal to INTEGER2
INTEGER1 -ge INTEGER2
              INTEGER1 is greater than or equal to INTEGER2
INTEGER1 -gt INTEGER2
              INTEGER1 is greater than INTEGER2
INTEGER1 -le INTEGER2
              INTEGER1 is less than or equal to INTEGER2
INTEGER1 -lt INTEGER2
              INTEGER1 is less than INTEGER2
INTEGER1 -ne INTEGER2
              INTEGER1 is not equal to INTEGER2

记忆方式还是比较简单的equal,greater,less,还是通过几个实例

4.1 磁盘分区情况

统计磁盘分区情况,计划每隔一天检查一次,若大于50%则邮件报警

[klaus@localhost chapt3]$ mail
No mail for klaus
[klaus@localhost chapt3]$ vim disk_warn.sh
[klaus@localhost chapt3]$ clear
[klaus@localhost chapt3]$ mail
No mail for klaus
[klaus@localhost chapt3]$ cat disk_warn.sh
#!/bin/bash

mail_user=klaus
disk_use=`df -Th|grep '/$'|awk '{print $6}'|awk -F "%" '{print $1}'`

if [ $disk_use -ge 50 ];then
    echo "Disk partition usage is greater than 50%!"
    echo "`date +%F-%H` disk:${disk_use}%" | mail -s "disk warning..." $mail_user
fi
[klaus@localhost chapt3]$ ./disk_warn.sh
Disk partition usage is greater than 50%!
[klaus@localhost chapt3]$ mail
Heirloom Mail version 12.4 7/29/08.  Type ? for help.
"/var/spool/mail/klaus": 1 message 1 new
>N  1 CenOS6                Sun Feb  2 23:18  18/639   "disk warning..."
& 1
Message  1:
From [email protected]  Sun Feb  2 23:18:02 2020
Return-Path: <[email protected]>
X-Original-To: klaus
Delivered-To: [email protected]
Date: Sun, 02 Feb 2020 23:18:01 -0800
To: [email protected]
Subject: disk warning...
User-Agent: Heirloom mailx 12.4 7/29/08
Content-Type: text/plain; charset=us-ascii
From: [email protected] (CenOS6)
Status: R

2020-02-02-23 disk:52%

然后用crondtab -e加入计划任务

4.2 内存报警

当内存使用量达到50%的时候,将报警信息写入对应的文件中去。

[klaus@localhost chapt3]$ mail
No mail for klaus
[klaus@localhost chapt3]$ ls
disk_warn.sh     mysqlback          usradd.sh
mem_use_warn.sh  test_mysqlback.sh  yum_httpap.sh
[klaus@localhost chapt3]$ cat mem_use_warn.sh
#!/bin/bash
mem_used=`free -m|grep '^Mem'|awk '{print $3}'`
men_total=`free -m|grep '^Mem'|awk '{print $2}'`
mem_percent=$[ mem_used*100/men_total ]

mail_user=klaus
warn_file=/home/klaus/Desktop/shell/chapt3/warn_memory.txt

rm -rf $warn_file
if [ $mem_percent -ge 50 ];then
    echo "`date +%F_%H` menmory: ${mem_percent}% " > $warn_file
fi

if [ -f $warn_file ];then
    mail -s "Warning, memory usage is greater than 50%!" $mail_user < $warn_file
    #rm -rf $warn_file
fi
[klaus@localhost chapt3]$ ./mem_use_warn.sh
[klaus@localhost chapt3]$ ls
disk_warn.sh     mysqlback          usradd.sh        yum_httpap.sh
mem_use_warn.sh  test_mysqlback.sh  warn_memory.txt
[klaus@localhost chapt3]$ cat warn_memory.txt
2020-02-03_00 menmory: 88%
[klaus@localhost chapt3]$ mail
Heirloom Mail version 12.4 7/29/08.  Type ? for help.
"/var/spool/mail/klaus": 1 message 1 new
>N  1 CenOS6                Mon Feb  3 00:27  18/670   "Warning, memory usage is greater than 50%!"

5.字符串比较

同样还是截取man test里面的内容

-n STRING
              the length of STRING is nonzero
STRING equivalent to -n STRING
-z STRING
              the length of STRING is zero
STRING1 = STRING2
              the strings are equal
STRING1 != STRING2
              the strings are not equal

-z表示字符串长度是0,-n表示字符串长度不为0,看一个简单的例子

[klaus@localhost chapt3]$ aaa=""
[klaus@localhost chapt3]$ echo ${#aaa}
0
[klaus@localhost chapt3]$ [ -z "$aaa" ];echo $?
0
[klaus@localhost chapt3]$ [ -n "$aaa" ];echo $?
1

这里有个小细节,为了避免未定义时,比较会报错,统一的加双引号,同时变量为0或者未定义时,长度都是0

5.1 实例,批量创建用户

[klaus@localhost chapt3]$ awk -F':' '{ print $1}' /etc/passwd
root
...
klaus
win
[klaus@localhost chapt3]$ cat batch_usradd.sh                  
#!/bin/bash
read -p "please input a number: " num
if [[ "$num" =~ ^[1-9][0-9]+$ ]];then
    echo "Wrong input parameters, please enter a numbers!"
    exit
fi

read -p "please input prefix: " prefix
if [ -z "$prefix" ];then
    echo "error prefix!"
    exit
fi

for i in `seq $num`
do
    user=$prefix$i
    sudo useradd $user
    echo "123456"|passwd --stdin $user &> /dev/null
    if [ $? -eq 0 ];then
        echo "user $user is created!"
    fi
done
[klaus@localhost chapt3]$ ./batch_usradd.sh                  
please input a number: 2
please input prefix: tmpuser
[klaus@localhost chapt3]$ awk -F':' '{ print $1}' /etc/passwd
root
...
klaus
win
user
tmpuser1
tmpuser2

上面设计一个正则的表达^[1-9][0-9]+$,表达式中的^表示以什么开头,$表示以什么结尾,+代表可以有多个,整个表达可表示成以非0开头的数字

6.模式匹配

case的语法结构为 case 变量 in
模式1)
命令序列
;;
模式2)
命令序列
;;
*)
无匹配后命令序列 esac

6.1 实例,删除用户,多匹配

具体思路,首先判断用户是否存在,若存在则询问是否删除,再次确定,执行删除操作

[klaus@localhost chapt3]$ sudo useradd alice
[klaus@localhost chapt3]$ cat delete_user.sh
#!/bin/bash
read -p "Please enter the username to delete:" user

id $user &> /dev/null
if [ $? -ne 0 ];then
    echo "Error, the user $user does not exist!"
    exit 1
fi

read -p "Are you sure to delete user $user ? [y/n]" action
case "$action" in
    y|Y|yes|YES)
        sudo userdel -r $user
        echo "user $user is deleted"
        ;;
    *)
        echo "Run error!"
esac
[klaus@localhost chapt3]$ ./delete_user.sh
Please enter the username to delete:alice
Are you sure to delete user alice ? [y/n]Y
user alice is deleted
[klaus@localhost chapt3]$ id alice
id: alice: No such user
[klaus@localhost chapt3]$ ./delete_user.sh
Please enter the username to delete:alice
Error, the user alice does not exist!

6.2 内存工具信息查看工具

[klaus@localhost chapt3]$ cat infor_tool.sh
#!/bin/bash

menu(){
    cat<<-EOF
##########################################
#   Linux Information Viewing Toolbox    #
#                                        #
#       h.  help                         #
#       f.  disk partition               #
#       d.  filesystem mount             #
#       m.  memory                       #
#       u.  system load                  #
#       q.  quit                         #
##########################################
EOF
}

menu
while :
do
    read -p "please input [ h for help ]: " action
    case "$action" in
        h)
            clear;menu;;#(建议下面都加一个clear操作)
        f)
            sudo fdisk -l;;
        d)
            df -Th;;
        m)
            free -m;;
        u)
            uptime;;
        q)
            break;;
       "")
            ;;
        *)
            echo "Run error!"
    esac
done

运行效果

[klaus@localhost chapt3]$ ./infor_tool.sh  
##########################################
#   Linux Information Viewing Toolbox    #
#                                        #
#       h.  help                         #
#       f.  disk partition               #
#       d.  filesystem mount             #
#       m.  memory                       #
#       u.  system load                  #
#       q.  quit                         #
##########################################
please input [ h for help ]: f

Disk /dev/sda: 21.5 GB, 21474836480 bytes
255 heads, 63 sectors/track, 2610 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x0003de16

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *           1          39      307200   83  Linux
Partition 1 does not end on cylinder boundary.
/dev/sda2              39        2358    18631680   83  Linux
/dev/sda3            2358        2611     2031616   82  Linux swap / Solaris
please input [ h for help ]: m
             total       used       free     shared    buffers     cached
Mem:           979        886         92          3         86        493
-/+ buffers/cache:        306        673
Swap:         1983          2       1981
please input [ h for help ]: q
[klaus@localhost chapt3]
发布了80 篇原创文章 · 获赞 86 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/klaus_x/article/details/104160814