何时将引号括在shell变量周围? [英] When to wrap quotes around a shell variable?

查看:98
本文介绍了何时将引号括在shell变量周围?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我是否应该在Shell脚本中的变量周围加上引号吗?

Could someone tell me whether or not I should wrap quotes around variables in a shell script?

例如,以下是否正确:

xdg-open $URL 
[ $? -eq 2 ]

xdg-open "$URL"
[ "$?" -eq "2" ]

如果是的话,为什么?

推荐答案

一般规则:如果它可以为空或包含空格(或实际上是任何空格)或特殊字符(通配符),则将其引号.不使用空格引用字符串通常会导致外壳将单个参数分解为多个参数.

General rule: quote it if it can either be empty or contain spaces (or any whitespace really) or special characters (wildcards). Not quoting strings with spaces often leads to the shell breaking apart a single argument into many.

$?不需要引号,因为它是一个数字值. $URL是否需要它取决于您在其中允许的内容以及是否为空的参数.

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

这篇关于何时将引号括在shell变量周围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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