Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does ash have an equivalent to bash's 'nullglob' option?

If a glob pattern doesn't match any files, bash will just return the literal pattern:

bash-4.1# echo nonexistent-file-*
nonexistent-file-*
bash-4.1#

You can modify the default behavior by setting the nullglob shell option so if nothing matches, you get a null string:

bash-4.1# shopt -s nullglob
bash-4.1# echo nonexistent-file-*

bash-4.1# 

So is there an equivalent option in ash?

bash-4.1# ash
~ # echo nonexistent-file-*
nonexistent-file-*
~ # shopt -s nullglob
ash: shopt: not found
~ # 
like image 825
eater Avatar asked Jan 29 '11 20:01

eater


2 Answers

For shells without nullglob such as ash and dash:

IFS="`printf '\n\t'`"   # Remove 'space', so filenames with spaces work well.

# Correct glob use: always use "for" loop, prefix glob, check for existence:
for file in ./* ; do        # Use "./*", NEVER bare "*"
    if [ -e "$file" ] ; then  # Make sure it isn't an empty match
        COMMAND ... "$file" ...
    fi
done

Source: Filenames and Pathnames in Shell: How to do it correctly (cached)

like image 124
Dennis Williamson Avatar answered Oct 25 '22 04:10

Dennis Williamson


This method is more performant than checking existence every iteration:

set q-*
[ -e "$1" ] || shift
for z; do echo "$z"
done

We use set to expand the wildcard into the shell's argument list. If the first element of the argument list is not a valid file, the glob didn't match anything. (Unlike some commonly seen attempts, this works correctly even if the glob's first match was on a file whose name is identical to the glob pattern.)

In case of no match, the argument list contains a single element, and we shift it off, so that the argument list is now empty. Then the for loop will not perform any iterations at all.

Otherwise, we loop over the list of arguments which the glob expanded into (this is the implicit behavior when there is no in elements after for variable).

like image 32
Zombo Avatar answered Oct 25 '22 02:10

Zombo