当环绕可变引号 [英] When to wrap quotes around a variable
问题描述
我在网上搜索,并不能找到一个答案,满足自己的好奇心。
I have searched the Internet and cannot find an answer to satisfy my own curiosity.
可能有人请告诉我,你是否应该环绕变量报价在shell脚本?
Could someone please tell me whether or not you should wrap quotes around variables in a shell script?
例如如下正确的:
xdg-open $URL
[ $? -eq 2 ]
或者
xdg-open "$URL"
[ "$?" -eq "2" ]
如果是这样,为什么?
And if so, why?
非常抱歉,如果这是一个愚蠢的问题,但我无法找到答案。
Very sorry if this is a stupid question, but I could not find an answer.
提前感谢大家!
推荐答案
一般规则:报价,如果它可以是空的或包含空格(或任何空白真的)。引述不带空格的字符串往往导致破壳分离的一个参数为多。
General rule: quote it if it can either be empty or contain spaces (or any whitespace really). Not quoting strings with spaces often leads to the shell breaking apart a single argument into many.
$?
,因为它是一个数值,不需要引号。无论 $网址
需要它取决于你允许在那里,你是否还希望有一个说法,如果它是空的。
$?
doesn't need quotes since it's a numeric value. Whether $URL
needs it depends on what you allow in there and whether you still want an argument if it's empty.
我倾向于时常引用字符串只是出于习惯,因为它的安全的方式。
I tend to always quote strings just out of habit since it's safer that way.
这篇关于当环绕可变引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!