Playing around today, I was trying to get grep to consume the output of...
$(apt-cache rdepends hunspell-fr | sed -e 's/^\s*|\?//' -e 1s/^/\'/g -e \$s/$/\'/)
...as a newline delimited list of patterns nested within single quotes. When I run the above command and then simply copy/paste the resulting output into a new grep command, it behaves as expected...
nohatsatthetable@debian:~$ dpkg -l | grep 'hunspell-fr
Reverse Depends:
hunspell-fr-classical
thunderbird-l10n-fr
firefox-esr-l10n-fr
thunderbird-l10n-fr
task-french-desktop
hunspell-fr-revised
hunspell-fr-revised
hunspell-fr-comprehensive
hunspell-fr-comprehensive
hunspell-fr-classical
firefox-esr-l10n-fr'
ii firefox-esr-l10n-fr 102.4.0esr-1~deb11u1 all French language package for Firefox ESR
ii hunspell-fr 1:7.0-1 all French dictionary for hunspell (dependency package)
ii hunspell-fr-classical 1:7.0-1 all French dictionary for hunspell (classical version)
ii task-french-desktop 3.68+deb11u1 all French desktop
However when I run the following one-liner, which to my eye should be functionally the same, grep only interprets the first line as a pattern, interpreting all subsequent lines (or words in the case of the second line) as the name of a directory or file to search within for the pattern...
nohatsatthetable@debian:~$ dpkg -l | grep $(apt-cache rdepends hunspell-fr | sed -e 's/^\s*|\?//' -e 1s/^/\'/g -e \$s/$/\'/)
grep: Reverse: No such file or directory
grep: Depends:: No such file or directory
grep: hunspell-fr-classical: No such file or directory
grep: thunderbird-l10n-fr: No such file or directory
grep: firefox-esr-l10n-fr: No such file or directory
grep: thunderbird-l10n-fr: No such file or directory
grep: task-french-desktop: No such file or directory
grep: hunspell-fr-revised: No such file or directory
grep: hunspell-fr-revised: No such file or directory
grep: hunspell-fr-comprehensive: No such file or directory
grep: hunspell-fr-comprehensive: No such file or directory
grep: hunspell-fr-classical: No such file or directory
grep: firefox-esr-l10n-fr': No such file or directory
Why does it behave in this way?
$(...)
expansion. This is possibly a duplicate of When is double-quoting necessary? – Kusalananda Nov 15 '22 at 17:10$()
being interpreted literally by the shell. This poses an even stranger question though; when filtered throughsed
, the output ofapt-cache
is encapsulated by single quotes, so what is the difference between that, and double quoting the command expansion (apart from the latter being infinitely more appropriate for the task at hand). Clearly there is a difference as one works and one doesn't, but I can't see what that difference is... – nohatsatthetable Nov 15 '22 at 17:59sed
and everything to do with how the shell is expanding the$()
. – terdon Nov 15 '22 at 19:17