通过在bash空变量 [英] pass empty variable in bash

查看:128
本文介绍了通过在bash空变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题:

 #!/斌/庆典功能testFunc(){
    回声参数#1:$ 1
    回声参数#2:$ 2
}参数1 =参数1
参数2 =参数2testFunc $参数1 $参数2

这路输出是:

 参数#1:参数1
参数#2:参数2

但是,当我设置参数1为空字符串:

 参数1 =

然后输出是休耕:

 参数#1:参数2
参数#2是:

我想这个问题是,当第一个参数是空的,其未声明,所以它实际上没有得到作为函数参数传递。

如果是这样的问题,那么有没有申报在bash变量空字符串的方式,或者是还有什么解决方法,以获得预期的行为?

注:按预期工作,如果我调用该函数是这样的:

  testFunct$参数2

但我要保持code干净。

更新:

我最近发现这引起了在情况下的误差未绑定变量是将要使用-u标志

  $的bash -u test.sh
参数#1:参数1
test.sh:5号线:$ 2:未绑定变​​量


解决方案

在你打电话与 testFunct参数2 脚本的第一个案例。因此,理解参数2 作为第一个参数。

它始终是可取的,以引号内传递参数,以避免这一点(说实话,对我来说是更清洁的这种方式)。所以,你可以把它叫做

  testFunct$参数1$参数2

示例

  $猫
#!/斌/庆典功能testFunc(){
    回声参数#1:$ 1
    回声参数#2:$ 2
}参数1 =
参数2 =参数2testFunc$参数1$参数2
$ ./a
参数#1是:
参数#2:参数2

my problem:

#!/bin/bash

function testFunc(){
    echo "param #1 is :" $1
    echo "param #2 is :" $2
}

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=""

Then the output is the fallowing:

param #1 is : param2
param #2 is :

I guess the problem is that when the first parameter is empty, its 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?

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.

$ bash -u test.sh
param #1 is : param1
test.sh: line 5: $2: unbound variable

解决方案

On the first case you call the script with testFunct param2. Hence, it understands param2 as the first parameter.

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"

Example

$ cat a
#!/bin/bash

function testFunc(){
    echo "param #1 is : $1"
    echo "param #2 is : $2"
}

param1=""
param2="param2"

testFunc "$param1" "$param2"


$ ./a
param #1 is :
param #2 is : param2

这篇关于通过在bash空变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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