条件查找输出丢失

Sha*_*war 3 command-line bash find

我试图构建一个条件语句来搜索特定大小的文件(在本例中为 1Gb。

if [ "find /location/sub/int/ -size +1G" ]
then
  > /location/sub/int/large_file_audit.txt
fi
Run Code Online (Sandbox Code Playgroud)

我运行它并创建一个文件,但该文件是空的,如何将查找结果填充到文件中?我究竟做错了什么?

ste*_*ver 6

您的测试if [ "find /location/sub/int/ -size +1G" ]没有按照您的预期工作,因为它测试了字符串 的非空性"find /location/sub/int/ -size +1G"- 这将始终为真。在任何情况下,重定向> /location/sub/int/large_file_audit.txt都不会神奇地获取前面命令的标准输出,因此将始终创建一个空文件。

也许最接近您在 Bash 中的意图是将结果find放入一个数组中,然后测试它是否有任何元素:

mapfile -t files < <(find /location/sub/int/ -size +1G)

if (( ${#files[@] > 0 )); then 
  printf '%s\n' "${files[@]}" > /location/sub/int/large_file_audit.txt
fi
Run Code Online (Sandbox Code Playgroud)

这不会优雅地处理包含换行符的文件名 - 使用较新版本的 bash,您可以将findmapfile空分隔,但如果您无论如何将它们作为换行分隔列表输出,则没有太大好处。