Do I need to quote command substitutions?

后端 未结 3 993
借酒劲吻你
借酒劲吻你 2021-01-05 22:44

According to the Google Shell Style Guide, I should:

Always quote strings containing variables, command substitutions, spaces or shell meta characters

3条回答
  •  长情又很酷
    2021-01-05 23:23

    $(echo foo bar) is indeed a command substitution. In this specific example, you don't need double quotes because a variable assignment creates a “double quote context” for its right-hand side, so VAR=$(…) is equivalent to VAR="$(…)".

    In bash, you don't need double quotes in export VAR=$(…) or declare VAR=$(…). But you do need the double quotes in some other sh implementations such as dash.

    You do need double quotes in env VAR=$(…) somecommand, in make VAR=$(…), etc. It isn't the equal sign that makes the double quotes optional, it's the fact that the equal sign is parsed by the shell as an assignment.

    There are a few other contexts where the double quotes are optional, but you can't go wrong with the simple rule: always use double quotes around variable and command substitutions unless you want the split+glob operator.

提交回复
热议问题