Home > database >  ZSH: How do I test whether a group of files exist or not?
ZSH: How do I test whether a group of files exist or not?

Time:11-16

I've got a group of files with only one specific extension under one specific directory. How do I check whether I've got at least one of those files. If at least one file with that specific extension is present, then print at least one file matching your extension is present in your directory. If not, then print no files of that specific extension exist in your directory.

Also, when no file of a specific extension is present, I've got the following error message that I'm not able to get rid of, even if I use 2>/dev/null redirection: zsh: no matches found: *.mkv (and hence, behaving differently from Bash)

CodePudding user response:

To disable the error, use the N glob qualifier to enable the NULL_GLOB option, replacing the error with an empty result.

% print *.mkv
zsh: no matches found: *.mkv
% print *.mkv(N)

%

For the rest of the problem, you can capture the result in an array named result, then get the number of matches by checking the size of the array with $#result.

If it would be useful, you can also limit which matches a pattern produces. For example, *.mkv[1,5] produces (at most) the first 5 results. The second number is optional; a single value only provides that one element.

CodePudding user response:

My problem solved as follows:

setopt no_nomatch
if ls *.mkv 1> /dev/null 2>&1; then echo OK; fi
setopt nomatch # Undo the change after evaluation (just in case)

Inspired by:

Good read on the topic:

https://scriptingosx.com/2019/06/moving-to-zsh-part-3-shell-options/

  • Related