我如何处理 null_glob 鱼的结果?

How do I handle null_glob results in fish?

我有一个包含以下 rm 语句的 fish 函数:

rm ~/path/to/dir/*.log

如果该路径中有 *.log 文件,此语句工作正常,但当没有 *.log 文件时失败。错误是:

~/.config/fish/functions/myfunc.fish (line 5): No matches for wildcard '~/path/to/dir/*.log'. See `help expand`.
    rm ~/path/to/dir/*.log
       ^
in function 'myfunc'
        called on standard input

ZSH 有所谓的Glob Qualifiers。其中之一,N,负责为当前模式设置 NULL_GLOB 选项,这基本上是我想要的:

If a pattern for filename generation has no matches, delete the pattern from the argument list instead of reporting an error.

我知道 fish 没有 ZSH-style glob qualifiers,但我不清楚如何在我的 fish 函数中处理这种情况。我应该遍历数组吗?看起来真的很冗长。还是有更可疑的方式来处理这种情况?

# A one-liner in ZSH becomes this in fish?
set -l arr ~/path/to/dir/*.log
for f in $arr
    rm $f
end

fish 不支持丰富的 glob,but count, set, and for are special 因为它们是 nullglob。所以你可以写:

set files ~/path/to/dir/*.log; rm -f $files

-f 是必需的,因为 rm 会在您传递零参数时抱怨。)

count 也可以:

count ~/path/to/dir/*.log >/dev/null && rm ~/path/to/dir/*.log

为了完整起见,一个循环:

for file in ~/path/to/dir/*.log ; rm $file; end