[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: reportbug: don't know: bug in apt [list] or in grep



On Thu, Jan 19, 2023 at 02:00:00PM +0100, DdB wrote:
> Am 19.01.2023 um 13:13 schrieb Greg Wooledge:
> > The fact that this *appears* to work is what causes so much confusion.
> > It will "work" some of the time, but not all of the time, and you'll
> > get different results depending on which directory you're in, on which
> > computer.
> > 
> > Bash has two other settings for handling unmatched globs.  The first one
> > is called "nullglob", and if it's turned on, an unmatched glob is simply
> > discarded from the command argument list.
> 
> I was really curious, how Greg would put words to this one. And i gotta
> applaud: Such unambiguous explanations, and so circumspect at the same
> time. Even understanding the basis for confusion, i could learn
> something new from this (other settings ...).

Regarding the nullglob and failglob settings:

failglob is pretty safe.  You can play around with that, and see how
it affects things.  Other shells have their equivalent enabled by
default, so it's basically a preference.

nullglob should not be used in an interactive shell.  There are far too
many tools that rely on the shell's normal behavior (passing along an
unmatched glob), and which will break if you turn on nullglob and then
type something innocuous.  The classic example, again, is ls.  If you
have nullglob enabled, and you do "ls *.ttx" or whatever typo, you'll
get the behavior of "ls" with no arguments, which shows all the files,
rather than an error message.

The only place where nullglob is useful is in a script, and even then,
it has to be a script where extra care is used.  I believe the intended
use case is something like this:

  for f in *.txt; do
    printf 'Processing "%s"...' "$f"
    process -- "$f" && echo ' done.'
  done

With nullglob enabled, if there are no matching *.txt files, the loop
is skipped.  Without nullglob, the *.txt will be unchanged, and the
loop body will be executed once, passing the literal '*txt' to the
printf and process commands.

There are several reasons why nullglob isn't on by default in scripts,
and isn't commonly used.  One of them is the same as with interactive
shells -- there are programs that may behave in a surprising way if
an unmatched glob is removed, rather than passed along.

Another reason is that you probably want to perform a basic sanity
check on your filenames before calling your "process" command.  The
glob might match things that aren't regular files -- directories, for
example, or FIFOs, which could cause "process" to fail or hang.  So,
you might prefer something like this:

  for f in *.txt; do
    test -f "$f" || continue
    printf 'Processing "%s"...' "$f"
    process -- "$f" && echo ' done.'
  done

Adding that basic sanity check also prevents processing an umatched
*.txt glob as a filename, so nullglob just isn't needed here.


Reply to: