在 Shell Script 要檢查檔案內容是否空白, 可以用 find 指令, 或者用 -s 參數檢查, -s 會在檢檔檔案存在及檔案體積大於 0 時, 回傳 TRUE, 否則回傳 FALSE.
find 指令
find 指令只要加上 -empty 參數, 就可以找出空白檔案, 例如要檢查 /home/phpini/tmp_file 是否空白檔案, 可以這樣做:
$ find /home/phpini -empty -name tmp_file
如果 /home/phpini/tmp_file 是空白檔案, 系統會回傳 /home/phpini/tmp_file, 如果 /home/phpini/tmp_file 有內容, 那麼 find 不會回傳結果。
Shell Script -s 參數
在 Shell Script 內檢查檔案是否空檔案, 除了用上面的 find 指令外, 也可以用 -s 參數, 具體寫法如下:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
#!/bin/sh filename="/home/phpini/tmp_file" if [ -s "$filename" ] then echo "$filename is NOT empty file." # 檔案有內容 else echo "$filename is empty file." # 空白檔案 fi |