toc

Shell 条件测试

文件测试

命令行使用方式

## 测试 /soft 目录是否存在,不存在就创建 /soft 目录
[root@Shell ~]# [ ! -d /soft ] && mkdir /soft
[root@Shell ~]# [ -d /soft ] || mkdir /soft

脚本使用方式

#!/usr/bin/bash
## 定义备份目录站点
dir=/soft/code
if [ ! -d $dir ];then
mkdir -p $dir
fi
ls $dir

数值比较

查看磁盘/当前使用状态,如果使用率超过80%则记录在 /tmp/disk_use.txt 文件(可以改成邮件报警)

#!/usr/bin/bash
Disk_Free=$(df -h|grep "/$"|awk '{print $5}'|awk -F '%' '{print $1}')
if [ $Disk_Free -ge 80 ];then
    echo "Disk Is Use:${Disk_Free}%" > /tmp/disk_use.txt
fi

逻辑判断

## 比较1小于2同时5大于10,两个条件必须都为真(and)
[root@Shell ~]# [ 1 -lt 2 -a 5 -gt 10 ];echo $?
[root@Shell ~]# [[ 1 -lt 2 && 5 -gt 10 ]];echo $?
## 比较1小于2同时5大于10,两个条件一个为真 (or)
[root@Shell ~]# [ 1 -lt 2 -o 5 -gt 10 ];echo $?
[root@Shell ~]# [[ 1 -lt 2 || 5 -gt 10 ]];echo $?

字符串比较

[root@Shell ~]# [ "$USER" = "root" ];echo $?
[root@Shell ~]# [ "$USER" != "nobody" ];echo $?
## 设个空值的变量,用-z和-n测试一下
[root@Shell ~]# BBB=""
[root@Shell ~]# [ -z "$BBB" ] ;echo $?
[root@Shell ~]# [ -n "$BBB" ] ;echo $?

正则对比

## 判断变量是不是以 **r** 开头的
[root@Shell ~]# [[ "$USER" =~ ^r ]];echo $?
## 判断变量是不是数字
[root@bgx]# num=123
[root@bgx]# [[ "$num" =~ ^[0-9]+$ ]];echo $?

批量创建用户脚本

#!/usr/bin/bash
read -p "Please input number: " num
if [[ ! "$num" =~ ^[0-9]+$ ]];then
    echo "error number!" && exit 1
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
    useradd $user
    echo "123" |passwd --stdin $user &>/dev/null
     if [ $? -eq 0 ];then
        echo "$user is created."
    fi
done
12-31 03:21
查看更多