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]