---
title: 【Shell Script】檢查檔案是否為空白
date: 2019-06-14
is_modified: false
disqus: cynthiahackmd
categories:
- "程式設計 › 程式語言與架構"
tags:
- "Shell Script"
---
{%hackmd @CynthiaChuang/Github-Page-Theme %}
<br>
在寫 Shell Script 時 ,想確定某檔案是否為空,若為空則想執行其他動作。
<!--more-->
## 1. **find**
直覺想到就是用 find 指令,加上 **empty** ,會回傳為空的檔案名稱,否則回傳空字串。
```bash
result=`find /home/user -type f -empty -name file.txt`
if [ "${result}" != "" ]; then
#do somethig...
fi
```
## 2. **Shell Script -s 參數**
除了用 find 指令外,另外找到一個 **-s** 參數,它會判斷若檔案存在且內容為空,則回傳 true ,否則回傳 false。
```bash
filename='/home/user/file.txt'
if [ ! -s "${filename}" ]; then
#do somethig...
fi
```
## 參考資料
1. [Shell Script 檢查檔案內容是否空白|LINUX 技術手札](https://www.opencli.com/linux/shell-script-check-file-content-empty)
<br><br>
> **本文作者**: 辛西亞.Cynthia
> **本文連結**: [辛西亞的技能樹](https://cynthiachuang.github.io/Checking-If-a-File-Is-Empty-in-a-Shell-Script) / [hackmd 版本](https://hackmd.io/@CynthiaChuang/Checking-If-a-File-Is-Empty-in-a-Shell-Script)
> **版權聲明**: 部落格中所有文章,均採用 [姓名標示-非商業性-相同方式分享 4.0 國際](https://creativecommons.org/licenses/by-nc-sa/4.0/deed.en) (CC BY-NC-SA 4.0) 許可協議。轉載請標明作者、連結與出處!