什么时候应该用引号将 shell 变量括起来? [英] When should I wrap quotes around a shell variable?

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

问题描述

我应该还是不应该在 shell 脚本中用引号将变量括起来?

Should or should I not wrap quotes around variables in a shell script?

例如,以下是否正确:

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

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

如果是,为什么?

推荐答案

一般规则:如果它可以为空或包含空格(或任何空格)或特殊字符(通配符),则引用它.不引用带空格的字符串通常会导致 shell 将单个参数分解为多个.

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天全站免登陆