[英]Can someone please help me with these shell script lines. I can' understand what is the use DEBUG in these lines
# Define DEBUG=true on cmdline, if needed DEBUG=${DEBUG:-false} [[ ${DEBUG} = true ]] || DEBUG="false"
The first assignment sets the variable DEBUG
to false
if the contents of DEBUG
is empty.如果
DEBUG
的内容为空,则第一个赋值将变量DEBUG
为false
。 Please note that if DEBUG
has not been initialized yet, it is also considered as empty and thus will receive the false
value.请注意,如果
DEBUG
还没有被初始化,它也被认为是空的,因此会收到false
值。
The second line uses the OR operator using ||
第二行使用 OR 运算符使用
||
, it is exactly the same as: ,它与以下完全相同:
if ! [[ ${DEBUG} = true ]]
then
DEBUG="false"
fi
In other words, it assigns the value false
to your variable if and only DEBUG
does NOT equal to true
.换句话说,当且仅当
DEBUG
不等于true
,它会将值false
分配给您的变量。
In the end, the purpose of this code is to define the DEBUG
variable to either true
or false
and nothing else, using the default value false
if the variable does not contain a boolean value.最后,这段代码的目的是将
DEBUG
变量定义为true
或false
,如果变量不包含布尔值,则使用默认值false
。
I think the first assignment is pointless because if the variable was empty at the beginning of this code, then the last line will assign the variable to false
anyways.我认为第一次赋值毫无意义,因为如果此代码开头的变量为空,那么最后一行无论如何都会将该变量赋值为
false
。
Also, the ${DEBUG}
should be protected with quotes, eg [[ "${DEBUG}" = true ]]
instead of [[ ${DEBUG} = true ]]
because your script may not work properly if the variable contains whitespaces.此外,
${DEBUG}
应该用引号保护,例如[[ "${DEBUG}" = true ]]
而不是[[ ${DEBUG} = true ]]
因为如果变量包含空格,您的脚本可能无法正常工作.
A bit overkill maybe, but I encourage checking case sensitivity and use a fallback code.可能有点矫枉过正,但我鼓励检查区分大小写并使用回退代码。
Let's say the user defines DEBUG=TRUE
(uppercase) prior to calling your script, the value of DEBUG
will be forced to false
.假设用户在调用脚本之前定义了
DEBUG=TRUE
(大写), DEBUG
的值将被强制为false
。 I guess the user would not be very pleased.我猜用户不会很高兴。
The following code solves all those issues:以下代码解决了所有这些问题:
# Define DEBUG=true on cmdline, if needed
DEBUG=${DEBUG,,} # Force the variable to lowercase
[[ "${DEBUG}" = true ]] || DEBUG=false
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.