Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
764 views
in Technique[技术] by (71.8m points)

bash - Do I need to quote command substitutions?

According to the Google Shell Style Guide, I should:

Always quote strings containing variables, command substitutions, spaces or shell meta characters, unless careful unquoted expansion is required.

Maybe I am misinterpreting what they mean by "command substitutions", but I am wondering if there is any need to use quotes in the following example:

VAR="$(echo foo bar)"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

$(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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...