Does ash have the equivalent of the bash option 'nullglob'?

If the glob pattern does not match any files, bash will simply return a literal pattern:

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

You can change the default behavior by setting the shell parameter nullglob , so if nothing matches, you will get an empty 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 ~ # 
+4
source share
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: File names and path names in the shell: how to do it correctly ( cached )

+3
source

This method is more efficient than checking for existence at each iteration:

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

We use set to extend the template in the shell argument list. If the first element of the argument list is not a valid file, glob does not match. (Unlike some common attempts, this works correctly, even if the first glob match was in a file whose name matches the glob pattern.)

If there is no match, the argument list contains one element, and we disable it so that the argument list is now empty. Then the for loop will not do any iteration at all.

Otherwise, we iterate over the list of arguments that extended glob (this is an implicit behavior when there is no in elements after for variable ).

+3
source

Source: https://habr.com/ru/post/1337611/


All Articles