user18685969
user18685969

Reputation:

Is there a ZSH equivalent to "shopt -s nullglob"?

I'm currently working on a script that deletes all the PNG files from my Desktop. I want to create an array of file paths then use the rm command on each one.

This is the relevant bit of code:

#!/usr/bin/env bash

shopt -s nullglob

files=("$HOME"/Desktop/*.png)
files_found="${#files[@]}"

shopt -u nullglob

It has been recommend that I use shopt in case of no matching files.

However I'm on MacOS and just discovered that shopt is not available for ZSH. When I run the script I get command not found: shopt.

I've found the ZSH has an equivalent called setopt however after reading through the documentation I can't quite figure out which option is the correct one to use in the case. I can't seem to find any examples either.

Can anyone point me in the right direction?

Upvotes: 7

Views: 7678

Answers (4)

Swiss
Swiss

Reputation: 5819

ZSH syntax allows users to modify the behavior of a glob by appending "Glob qualifiers". This allows the Null Glob option to be easily set for one specific glob. Simply put (...) at the end of your glob containing the qualifiers you want to use.

The N flag enables Null Globbing, so enabling Null Glob on your given glob would be done as follows:

files=("$HOME"/Desktop/*.png(N))

You can find a full list of Glob Qualifiers under "Glob Qualifiers" in the ZSH documentation.

Upvotes: 0

user1934428
user1934428

Reputation: 22301

The more zsh-like approach is not to set this as a general option (as suggested in the answer given by chepner), but to decide on each pattern, whether or you want to have the nullglob effect. For example,

for f in x*y*(N)
do
  echo $f
done

simply skips the loop if there are no files matching the pattern.

Upvotes: 8

user18685969
user18685969

Reputation:

Just come to the realisation that the issue of shopt not being found was due to me auto-loading the file as a ZSH function.

The script worked perfectly when I ran it like so:

bash ./tidy-desktop

Previously I had been running it just with the command tidy-desktop

Instead I now have this in my zsh_aliases:

tidy-desktop="~/.zshfn/tidy-desktop"

Thanks to @Charles Duffy for helping me figure out what was going on there!

Upvotes: -3

chepner
chepner

Reputation: 532093

The corresponding option in zsh is CSH_NULL_GLOB (documented in man zshoptions).b

 setopt CSH_NULL_GLOB

(As far as I can tell, the idea of a pattern disappearing rather than being treated literally comes from csh.)

Upvotes: 10

Related Questions