用于查找文件是否为空的选项或命令

Zia*_*ary 4 command-line files

是否有一个命令可以找出文件是否包含某些内容?

我尝试使用ls' size 选项 ( ls -lsh) 但它没有显示空文件,因为文件/文件夹没有大小。

kos*_*kos 9

您可以使用testwith-f! -s0如果存在空的常规文件或1其他情况,它将返回:

-f FILE
    FILE exists and is a regular file
-s FILE
    FILE exists and has a size greater than zero
Run Code Online (Sandbox Code Playgroud)
test -f file -a ! -s file && printf 'File exists and is empty.\n'
Run Code Online (Sandbox Code Playgroud)

或者使用更常见的语法:

[ -f file -a ! -s file ] && printf 'File exists and is empty.\n'
Run Code Online (Sandbox Code Playgroud)
$ touch empty
$ printf '\n' >non_empty
$ test -f file -a ! -s empty && printf 'File exists and is empty.\n'
File exists and is empty.
$ test -f file -a ! -s non_empty && printf 'File exists and is empty.\n'
$ 
Run Code Online (Sandbox Code Playgroud)

~/.bashrc为方便起见,您可以添加一个函数:

is_empty() { test -f file -a ! -s file && printf 'File exists and is empty.\n'; }
Run Code Online (Sandbox Code Playgroud)

或者使用更常见的语法:

is_empty() { [ -f file -a ! -s file ] && printf 'File exists and is empty.\n'; }
Run Code Online (Sandbox Code Playgroud)
$ touch empty
$ printf '\n' >non_empty
$ is_empty empty 
File exists and is empty.
$ is_empty non_empty 
$ 
Run Code Online (Sandbox Code Playgroud)