Regex interpretation needed

# is supposed to comment out everything following
That does not make sense

Bash probably treats the # differently if it’s within quotes. I remember something about variable expansion being suppressed when within either single quotes or double quotes.

2 Likes

Correct, there’s no expansion, globbing, anything within single quotes. The shell leaves all that alone and delivers it verbatim to the command. (Double-quotes also disable globbing, but not expansion.) Observe:

$ ls "*.txt"
ls: cannot access '*.txt': No such file or directory
$ ls "$HOME"
<contents of my home directory>
$ ls '$HOME'
ls: cannot access '$HOME': No such file or directory
$ echo ${HOME//ferd}
/home/
$ echo "${HOME//ferd}"
/home/
$ echo '${HOME//ferd}'
${HOME//ferd}
$ echo "$((3 + 2))"
5
$ echo '$((3 + 2))'
$((3 + 2))

Operators like pipes and redirects will also lose their effect within either single or double quotes:

$ echo "Hi|there"
Hi|there
$ echo "Hi >/dev/null"
Hi >/dev/null
$ echo "Hi && exit"
Hi && exit
5 Likes

Oh, I forgot a very important exception to that: Line continuations. In an unquoted command line, a newline will end the command. You can use \ at the end of the line to continue the command on the next line. That works normally in double quotes (to continue the quoted argument on the following line). It does not work inside single quotes. But, you can embed newlines in either type of quoted argument by simply inserting them without any special escaping/markup. An unescaped newline will not implicitly end the command if you’re inside open single/double quotes, it’ll simply become part of the quoted string.

(The > at the start of some input lines below is the Bash continuation prompt, it appears before input lines that continue a command started on the preceding line(s).)

$ echo Hi \
> there
Hi there
$ echo "Hi
> there"
Hi
there
$ echo "Hi \
> there"
Hi there
$ echo 'Hi
> there'
Hi
there
$ echo 'Hi \
> there'
Hi \
there
4 Likes