如何检查文件是空的还是只有空白字符?

yae*_*ael 6 shell files

如果文件为空,这将通知我们:

[[ ! -s $file ]] && echo "hello there I am empty file !!!"
Run Code Online (Sandbox Code Playgroud)

但是如何检查文件是否有空格(空格或制表符)?

  • 空文件可以包含空格/TAB

xhi*_*nne 19

grep适用于空格以外的字符:

grep -q '[^[:space:]]' < "$file" &&
  printf '%s\n' "$file contains something else than whitespace characters"
Run Code Online (Sandbox Code Playgroud)


小智 5

与其他答案类似,但使用否定grep -q

if ! grep -q '[^[:space:]]' "$file"; then
    echo "file is empty"
else
    echo "File has data"
fi
Run Code Online (Sandbox Code Playgroud)