string 在bash中传递空变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19376648/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pass empty variable in bash
提问by kupsef
My problem:
我的问题:
#!/bin/bash
function testFunc(){
echo "param #1 is :"
echo "param #2 is :"
}
param1="param1"
param2="param2"
testFunc $param1 $param2
This way the output is:
这样输出是:
param #1 is : param1
param #2 is : param2
But when I set param1 to empty string:
但是当我将 param1 设置为空字符串时:
param1=""
Then the output is the following:
然后输出如下:
param #1 is : param2
param #2 is :
I guess the problem is that when the first parameter is empty, it's not declared, so it actually doesn't get passed as a function parameter.
我想问题是当第一个参数为空时,它没有被声明,所以它实际上不会作为函数参数传递。
If that is the problem, then is there a way to declare a variable "empty string" in bash, or is there any workaround to get the expected behavior?
如果这是问题,那么有没有办法在 bash 中声明变量“空字符串”,或者是否有任何解决方法来获得预期的行为?
Note: It works as expected if I call the function like this:
注意:如果我像这样调用函数,它会按预期工作:
testFunct "" $param2
But I want to keep the code clean.
但我想保持代码干净。
UPDATE:
更新:
I recently discovered the -u
flag which raises an error in case an unbound variable is about to be used.
我最近发现-u
了一个标志,它会在即将使用未绑定变量的情况下引发错误。
$ bash -u test.sh
param #1 is : param1
test.sh: line 5: : unbound variable
回答by fedorqui 'SO stop harming'
On the first case you call the script with testFunct param2
. Hence, it understands param2
as the first parameter.
在第一种情况下,您使用testFunct param2
. 因此,它被理解param2
为第一个参数。
It is always recommendable to pass parameters within quotes to avoid this (and to be honest, for me it is cleaner this way). So you can call it
始终建议在引号内传递参数以避免这种情况(说实话,对我来说,这种方式更干净)。所以你可以调用它
testFunct "$param1" "$param2"
So to pass an empty variable you say:
所以要传递一个空变量,你说:
testFunct "" "$param2"
See an example:
看一个例子:
Given this function:
鉴于此功能:
function testFunc(){
echo "param #1 is -> "
echo "param #2 is -> "
}
Let's call it in different ways:
让我们以不同的方式调用它:
$ testFunc "" "hello" # first parameter is empty
param #1 is ->
param #2 is -> hello
$ testFunc "hey" "hello"
param #1 is -> hey
param #2 is -> hello
回答by Tom Ron
Another best practice is to check the number of parameters passed using $#.
另一个最佳实践是检查使用 $# 传递的参数数量。
However, this does not solve the problem of one empty parameter, how would you know if the param1 is empty or param2 is empty. Therefore both checks are good parctices.
但是,这并没有解决一个空参数的问题,你怎么知道param1是空的还是param2是空的。因此,这两项检查都是很好的检查。