什么时候应该双引号参数扩展? [英] When should I double-quote a parameter expansion?

查看:78
本文介绍了什么时候应该双引号参数扩展?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个变量x.展开时,应该使用$x还是"$x"?

Say I have a variable x. When expanding it, should I use $x or "$x"?

(这旨在作为围绕无引号参数扩展的任何问题的规范重复.)

(This is intended as a canonical duplicate for any question that revolves around unquoted parameter expansions.)

推荐答案

始终至少在开始时始终使用"$x". far 正确的情况要多于可能错误的情况.

Always use "$x", at least at first. The cases where this is correct far outnumber the cases where it may be wrong.

参数扩展同时受单词拆分和路径名扩展的约束,这两个都不是您通常需要的.引用扩展保留参数的文字内容.

Parameter expansions are subject to both word-splitting and pathname expansion, neither of which you usually want. Quoting the expansion preserves the literal content of the parameter.

比较

$ x="foo * bar"
$ printf '%s\n' "$x"
foo * bar

$ printf '%s\n' $x
foo
<every file in the current directory>
bar

如果您的逻辑确实需要进行单词拆分或扩展路径名,则很有可能需要更改脚本设计以避免该要求.

If your logic does require word-splitting or pathname expansion to take place, there is a good chance that your script design needs to be changed to avoid that requirement.

总是引用参数扩展,至少会减少您需要修复的错误的数量.

Always quoting parameter expansions will, at the very least, reduce the number of bugs you need to fix.

作为推论,从不没有理由使用${foo[@]}不加引号. @索引的确存在是被引用时具有特殊的行为(与*索引相比).如果不加引号,则两者是相同的,因此您也可以使用${foo[*]}.

As a corollary, there is never a reason to use ${foo[@]} unquoted. The very existence of @ indexing is to have special behavior (compared to * indexing) when quoted. When unquoted, the two are identical, so you may as well use ${foo[*]}.

相同的参数适用于特殊参数$@$*.

The same argument applies to the special parameters $@ and $*.

$ x=("foo bar" baz)
$ printf '%s\n' "${x[@]}"  # expands to two elements words, one per element
foo bar
baz
$ printf '%s\n' "${x[*]}"  # expands to one word; elements join using IFS
foo bar baz
$ printf '%s\n' ${x[*]}    # expands to three words
foo
bar
baz

这篇关于什么时候应该双引号参数扩展?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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