Avoiding errors due to unexpanded asterisk

Yes, run the following command :

shopt -s nullglob

it will nullify the match and no error will be triggered.

  • if you want this behaviour by default, add the command in your ~/.bashrc
  • if you want to detect a null glob in POSIX shell, try

    for i in *.txt; do
      [ "$i" = '*.txt' ] && [ ! -e '*.txt' ] && continue
    done
    

See http://mywiki.wooledge.org/NullGlob


In bash you can use shopt -s nullglob to expand to an empty array if there are no matches.

In POSIX shells without nullglob, you can avoid this problem by checking that the filename being passed actually exists by having [ -e "$file" ] || [ -L "$file" ] || continue as the first part of your for loop.


The usual technique for shells that don't have a nullglob option is

set -- [*].type *.type
case $1$2 in
  '[*].type*.type') shift 2;;
  *) shift
esac
for file do
  cmd  -- "$file"
done

The extra [*].type is to cover the case where there's one file called *.type in the current directory.

Now, if you want to include dot files, that becomes more complicated.

I beleive that technique was coined by Laura Fairhead on usenet a few years ago.