Skip to main content

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

4
  • Thank you for answer. Is it kind of an inconsistent behaviour of Bash that if a pattern (in the unquoted variable) is not treated as a glob, the backslash will not be discarded? It is because if the pattern is not in a variable, ls sec\*et matches sec*et literally. Any docs in POSIX or Bash mentioning this? As my first comment in the question, I still wonder if it is because variable versus plain pattern they undergo different expansions. This behaviour is too specific that I need more explanations. I afraid I might face other corner cases in the future. Commented Jan 18, 2024 at 4:55
  • @midnite ls sec\*et doesn't "match" anything, because sec\*et is not a glob, so there's nothing to match. Again, try with failglob set and without a matching file, it will not complain. Here, the resulting argument to ls is sec*et because the rules for unquoted words in the command line say that the backslash quotes the following character, it's exactly the same as sec"*"et. I'm not sure why it's inconsistent that the backslash isn't discarded? It's not like the shell discards any other characters from values that result from expansions, either, right? Commented Jan 18, 2024 at 7:17
  • The reference manual does say that "After word splitting, unless the -f option has been set (see The Set Builtin), Bash scans each word for the characters *, ?, and [. If one of these characters appears, and is not quoted, then the word is regarded as a pattern, and replaced with an alphabetically sorted list of filenames matching the pattern (see Pattern Matching)." (I expect escaping with a backslash counts as being quoted here, too, but I suppose you'll need to ask the maintainer if that's a question.) Commented Jan 18, 2024 at 7:18
  • Anyway, as Stéphane mentioned, the behavior has varied between shells and shell versions (and IMO, it's not like the shell languages are exactly straightforward in other sense anyway), so it might be easier to just avoid cases like that. If [*] works for what you want, being unquestionably a glob that only matches a literal asterisk, why not use that? Commented Jan 18, 2024 at 7:22