Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I handle null_glob results in fish?

Tags:

fish

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
like image 914
mattmc3 Avatar asked Nov 05 '19 22:11

mattmc3


People also ask

Is fish compatible with bash?

Regular bash scripts can be used in fish shell just as scripts written in any language with proper shebang or explicitly using the interpreter (i.e. using bash script.sh ). However, many utilities, such as virtualenv, modify the shell environment and need to be sourced, and therefore cannot be used in fish.

What is config fish?

Description. fish_config is used to configure fish. Without arguments or with the browse command it starts the web-based configuration interface. The web interface allows you to view your functions, variables and history, and to make changes to your prompt and color configuration.


1 Answers

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
like image 186
ridiculous_fish Avatar answered Nov 20 '22 08:11

ridiculous_fish