2021年6月14日 星期一

Linux Shell Script 檢查檔案內容是否空白

 1. find,使用-empty 參數,若檢查檔案是空白檔案,會回傳該檔案名稱,若檢查檔案有內容,則不回傳解果

:~# ls -l

total 2172

-rwxr--r-- 1 nobody nogroup 1050407 May 16 22:08 access.log

-rw-r--r-- 1 root   root          0 Jun 14 12:19 BadIP.txt

-rwxr--r-- 1 root   root       2019 May 23 23:36 BanBadIP.sh

-rw-r--r-- 1 root   root         33 May 17 10:54 banip.sh

-rw-r--r-- 1 root   root          0 May 16 21:45 ip_file

root@mail:~# find . -empty -name BadIP.txt

./BadIP.txt

root@mail:~# find . -empty -name banip.sh

root@mail:~# 


2.使用Shell Script -s 參數

#!/bin/sh
 
filename="/tmp/tmp_file"
 
if [ -s "$filename" ]
then
echo "$filename is NOT empty file."
        # 檔案有內容
else
echo "$filename is empty file."
        # 空白檔案
fi