3

With zsh, it is not difficult to create a possibly empty array from the results of a (possibly null) filename glob. For example:

% pathlist=( /no/such/path/*(N) ); printf -- "%d\n" $#pathlist
0

With bash, however, the closest approximation I can come up with to the code above fails to produce an empty array when the glob is null:

% pathlist=( /no/such/path/*    ); printf -- "%d\n" ${#pathlist[@]} )
1

In this case, the pathlist variable contains a single entry, namely the string "/no/such/path/*".

How can I modify the bash code so that pathlist contains exactly one entry for every file (if any) that matches the glob?

7

You need to use the shell option nullglob

#!/bin/bash
shopt -s nullglob
pathlist=( /no/such/path/*    ); printf -- "%d\n" "${#pathlist[@]}" )
shopt -u nullglob

The Bash manual says the following about the nullglob shell option:

If set, Bash allows filename patterns which match no files to expand to a null string, rather than themselves.

  • 2
    note declare -p pathlist is a nice way to dump an array variable. – glenn jackman Feb 26 '18 at 23:30
  • @glennjackman: Where would that fit into the answer? – Jesse_b Feb 26 '18 at 23:35
  • Instead of the printf... – Jeff Schaller Feb 26 '18 at 23:56
  • OP is using printf to simply print the number of elements in the array though, not a declare statement for it...If anything it would be better written as simply echo "${#pathlist[@]}" – Jesse_b Feb 27 '18 at 0:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.