如何处理鱼中的null_glob结果?

我有一个包含以下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选项,这实际上是我想要的:

  

如果用于文件名生成的模式不匹配,请删除   从参数列表中选择模式,而不是报告错误。

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

# A one-liner in ZSH becomes this in fish?
set -l arr ~/path/to/dir/*.log
for f in $arr
    rm $f
end
dajiaonline 回答:如何处理鱼中的null_glob结果?

fish不支持丰富的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
本文链接:https://www.f2er.com/3156098.html

大家都在问