Zia*_*ary 4 command-line files
是否有一个命令可以找出文件是否包含某些内容?
我尝试使用ls
' size 选项 ( ls -lsh
) 但它没有显示空文件,因为文件/文件夹没有大小。
您可以使用test
with-f
和! -s
,0
如果存在空的常规文件或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)