问题
I have a fish function that contains the following rm
statement:
rm ~/path/to/dir/*.log
This statement works fine if there are *.log files in that path, but fails when there are no *.log files. The error is:
~/.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 has what are called Glob Qualifiers. One of them, N
, handles setting the NULL_GLOB option for the current pattern, which essentially does what I want:
If a pattern for filename generation has no matches, delete the pattern from the argument list instead of reporting an error.
I understand that fish doesn't have ZSH-style glob qualifiers, but I am unclear how to handle this scenario in my fish functions. Should I be looping through an array? It seems really verbose. Or is there a more fishy way of handling this scenario?
# A one-liner in ZSH becomes this in fish?
set -l arr ~/path/to/dir/*.log
for f in $arr
rm $f
end
回答1:
fish does not support rich globs, but count, set, and for are special in that they nullglob. So you could write:
set files ~/path/to/dir/*.log; rm -f $files
(The -f
is required because rm
complains if you pass it zero arguments.)
count
could also work:
count ~/path/to/dir/*.log >/dev/null && rm ~/path/to/dir/*.log
For completeness, a loop:
for file in ~/path/to/dir/*.log ; rm $file; end
来源:https://stackoverflow.com/questions/58720232/how-do-i-handle-null-glob-results-in-fish