简体   繁体   English

在BASH配置文件中定义变量的最佳实践

[英]Best practice for defining variables in BASH configuration files

I read in http://wiki.bash-hackers.org/howto/conffile that it is recommended to put double quotes around values in BASH configuration files which are to be sourced into a script. 我在http://wiki.bash-hackers.org/howto/conffile中读到,建议在要导出到脚本的BASH配置文件中的值周围加上双引号。

The file to be sourced should be formated in key="value" format, otherwise bash will try to interpret commands 要获取的文件应设置为key =“ value”格式,否则bash会尝试解释命令

However, I am not aware of any difference in BASH's behavior when sourcing a configuration file if the value has double quotes or not, assuming there is no whitespace in the value. 但是,假设值中没有空格,则无论该值是否带有双引号,我在采购配置文件时都不会意识到BASH的行为有什么不同。 I'm sure there are some more complex cases where the double quotes are vital (eg using other variables as the value), but for the simple cases below, would double quotes cause BASH to behave any differently, even if the difference is only behind-the-scenes? 我确信在某些更复杂的情况下,双引号至关重要(例如,使用其他变量作为值),但是对于下面的简单情况,双引号会导致BASH的行为有所不同,即使差异仅在后面-THE幕后? I'm wondering if the first configuration file below could cause BASH to search for a named foobar before assigning it as a string, but from my testing it doesn't appear to do so. 我想知道下面的第一个配置文件是否可能导致BASH在将其分配为字符串之前搜索命名的foobar,但是从我的测试来看,它似乎没有这样做。

# Configuration file 1
myDir=/var/tmp/test/
myString=foobar
myInteger=20

# Configuration file 2
myDir="/var/tmp/test/"
myString="foobar"
myInteger="20"

source configurationFile1
echo "$myDir"
echo "$myString"
echo "$myInteger"

source configurationFile2
echo "$myDir"
echo "$myString"
echo "$myInteger"

It's a style issue. 这是一个风格问题。 In the examples you show, the quotes aren't strictly necessary. 在您显示的示例中,引号不是严格必需的。 myDir=/var/tmp/text and myDir="/var/tmp/text" do exactly the same thing. myDir=/var/tmp/textmyDir="/var/tmp/text" 完全相同 Other values may require quotes to make the assignment correct. 其他值可能需要加引号以使分配正确。

The allusion is to the fact that these aren't really configuration files; 暗示这些不是真正的配置文件; they're just bash scripts that are intended to contain only assignments. 它们只是旨在仅包含分配的bash脚本。 Something like 就像是

foo=bar baz

is not an assignment; 不是作业; it's a simple command that tries to run baz with a variable named foo in its environment. 这是一个简单的命令,试图在其环境中使用名为foo的变量运行baz Here, quotes are required: 在这里,引号必需的:

foo="bar baz"

to make a proper assignment, in contrast to other "actual" configuration file formats where everything following the = (and optionally some post- = whitespace`) is considered part of the value to be assigned. 与其他“实际”配置文件格式相反,在其他“实际”配置文件格式中, = (以及可选的某些post- =空格)之后的所有内容均被视为要分配的值的一部分,因此可以进行适当的分配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM