Nested quotes in subshells

11,051

Solution 1

You don't need to escape the quotes inside a subshell, since the current shell doesn't interpret them (it doesn't interpret anything from $( to ), actually), and the subshell doesn't know about any quotes that are above.

Quoting a subshell at variable assignment is unnecessary too, for more info see man bash.

Solution 2

You don't need to escape the nested quotes inside. They get parsed properly, surprisingly!

DATA="$(cat file.hex | xxd -r | tr -d "$(cat trim.txt)")"
Share:
11,051

Related videos on Youtube

Melab
Author by

Melab

Updated on September 18, 2022

Comments

  • Melab
    Melab almost 2 years

    Say I have to use quotes to encapsulate subshell output like:

    DATA="$(cat file.hex | xxd -r)"
    

    But I need to nest this kind of stuff like:

    DATA="$(cat file.hex | xxd -r | tr -d \"$(cat trim.txt)\")"
    

    I can't use single quotes because those do not expand variables that are inside of them. Escaping quotes doesn't work because they are just treated as passive text.

    How do I handle this?

    • cuonglm
      cuonglm about 9 years
      Why don't you use DATA="$(cat file.hex | xxd -r | tr -d "$(cat trim.txt)")"?
  • LPCRoy
    LPCRoy over 8 years
    It depends on what you're trying to do, but it's usually a best practice. See github.com/koalaman/shellcheck/wiki/Sc2086
  • jmrah
    jmrah about 4 years
    Why is quoting a subshell at variable assignment unnecessary?
  • Pedro A
    Pedro A about 3 years
    So if I want to have a ) in the subcommand, should I escape the )?
  • palswim
    palswim almost 3 years
    My man bash says "If the substitution appears within double quotes, word splitting and pathname expansion are not performed on the results." (in EXPANSION > Command Substitution). That seems to imply that we would need to quote subshell invocations.