Sanghai
Sanghai

Reputation: 57

use asterisk inside variable in zsh function

In my zsh, I've defined a function

a() { local x=*.proto; ls "$x"; }

when i hit a in my terminal, got

Specified path '*.proto' doesn't exist.

My directory ooks like:

hello.proto

How can I pass the wildcard match?

Upvotes: 1

Views: 373

Answers (1)

Inian
Inian

Reputation: 85693

Use an array and expand the glob results inside it using printf(). Like nullglob on bash, the zsh shell has an null_glob option to silently exit on expansion failure. So putting it all together

a() {
   # Turing on the option to prevent glob expansion failure
   setopt null_glob
   # Put the results to an array, so that a quoted expansion would keep the
   # filename containing shell meta-characters intact
   local x=(*.proto)
   # Print the array if it is non-empty.
   (( "${#a[@]}" )) && printf '%s\n' "${x[@]}"
}

Upvotes: 1

Related Questions