[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: Why echo without quotes need to glob the file
From: |
Greg Wooledge |
Subject: |
Re: Why echo without quotes need to glob the file |
Date: |
Tue, 13 Dec 2022 22:10:08 -0500 |
On Wed, Dec 14, 2022 at 10:51:09AM +0800, wang yuhang wrote:
> on Tue, 13 Dec 2022 09:15:53 -0500 Greg Wooledge via wrote:
> > [--hello] is an example of a "glob", which is a pattern that can match
> > one or more filenames. Other examples of globs are *.txt or foobar.[ch]
> > Since your glob is not quoted, the shell expands it to a list of
> filenames
> > that it matches in the current directory.
> > If you want [--hello] NOT to be expanded, put quotes around it. Either
> > single quotes or double quotes will do.
>
> I konw the right thing to do is put quotes around it, I just don't
> understand that bash regards [-- hello] as a glob to match filenames in `echo`
Any argument that contains "*", or "?", or both of the "[" and "]"
characters in that order, will be treated as a glob, if those characters
are not quoted.
In a command like this:
echo Do you want food?
The argument "food?" is a glob, because it contains an unquoted "?"
character. It will be matched against files in the current directory,
and could be replaced by a list of filenames.
The same goes for "[--hello]" which contains the "[" and "]" characters.
The same goes for commands like this one:
unset array[1]
The argument "array[1]" is treated as a glob. IF there happens to be
a file named "array1" in the current directory, then the glob is
replaced, and you end up running this instead:
unset array1
This has a different meaning, and doesn't do what you want.
To get the correct results, any string that *could* be seen as a glob
needs to be quoted. Or at the very least, the special glob characters
need to be quoted.
echo Do you want food\? # This one is safe. But weird.
echo Do you want "food?" # Also weird.
echo "Do you want food?" # Much more normal.
unset "array[1]" # Annoying? Yes, very. But necessary.
It's worth developing the habit of always putting quotes around messages
that you pass to echo for printing. There's virtually never a time you
want any part of a message to undergo word splitting or globbing.