我需要引用命令替换吗? [英] Do I need to quote command substitutions?

查看:50
本文介绍了我需要引用命令替换吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 Google Shell样式指南,我应该:

除非需要仔细的用引号引起来的扩展,否则总是引用包含变量,命令替换,空格或shell元字符的字符串.

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)"

推荐答案

$(echo foo bar)确实是命令的替代.在此特定示例中,您不需要双引号,因为变量赋值为其右侧创建了一个双引号上下文",因此VAR=$(…)等效于VAR="$(…)".

$(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="$(…)".

在bash中,export VAR=$(…)declare VAR=$(…)中不需要双引号.但是在某些其他sh实现(例如破折号)中,确实需要双引号.

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.

env VAR=$(…) somecommandmake VAR=$(…)等中确实需要双引号.并不是使双引号成为可选的等号,这是由外壳解析等号作为赋值的事实.

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.

还有一些其他情况下,双引号是可选的,但是您不会错失简单的规则:您需要split + glob运算符.

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.

这篇关于我需要引用命令替换吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆