help-bash
[Top][All Lists]
Advanced

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

Re: Why echo without quotes need to glob the file


From: G. Branden Robinson
Subject: Re: Why echo without quotes need to glob the file
Date: Tue, 13 Dec 2022 08:28:25 -0600

At 2022-12-13T20:45:36+0800, wang yuhang via wrote:
> There are some bad smelling codes in the shell scripts of my company's
> products。 
[...]
> $ echo [--hello]
> [--hello]
> $ touch 1
> $ echo [--hello]
> 1
> 
> I know the main reason is that my some code is poorly written. from
> another perspective, the builtin command `echo` has nothing to do with
> file, but it still uses regular expressions to glob the file. I
> don't quite understand this behavior。

As Greg pointed out, "echo" isn't doing any pattern-matching here, the
shell is.  If you run an external command called "echo", e.g.,
"/bin/echo" and inspect its argument list with strace(1), you can see
this.  (On my system, it shows up as the first line, in "execve()".

> Could you tell me the reason for the original design ?

That would be a good question for the TUHS mailing list; perhaps John
Mashey or Steve Bourne, or someone who worked with them at the Bell Labs
CSRG in the 1970s, could advise on their motivations.

What's also happening here is an unusual glob pattern that looks like a
GNU-style "long option" in the option notation used by man pages.  But
that's an illusion; it's a "glob".  See glob(7).

It matches any file names matching the single letters "e", "l", and "o",
plus single-character file names in the _range "-" to "h".

From ascii(7), we can see why "1" matches.

      30 40 50 60 70 80 90 100 110 120
     ‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐‐
    0:    (  2  <  F  P  Z  d   n   x
    1:    )  3  =  G  Q  [  e   o   y
    2:    *  4  >  H  R  \  f   p   z
    3: !  +  5  ?  I  S  ]  g   q   {
    4: "  ,  6  @  J  T  ^  h   r   |
    5: #  -  7  A  K  U  _  i   s   }
    6: $  .  8  B  L  V  `  j   t   ~
    7: %  /  9  C  M  W  a  k   u  DEL
    8: &  0  :  D  N  X  b  l   v
    9: '  1  ;  E  O  Y  c  m   w

"1" lies between "-" and "h".  It seems that in most shells (I tried
bash, ksh93, dash, yash, and zsh) a leading dash in a glob bracket
expression is treated as a range bound.  This may be mandated by POSIX
but I'll leave that question for another contributor.

Regards,
Branden

Attachment: signature.asc
Description: PGP signature


reply via email to

[Prev in Thread] Current Thread [Next in Thread]