28

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 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?

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
4

3 回答 3

44

在第一种情况下,您使用testFunct param2. 因此,它被理解param2为第一个参数。

始终建议在引号内传递参数以避免这种情况(老实说,对我来说,这种方式更干净)。所以你可以调用它

testFunct "$param1" "$param2"

所以要传递一个空变量,你说:

testFunct "" "$param2"

看一个例子:

鉴于此功能:

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

让我们以不同的方式称呼它:

$ testFunc "" "hello"    # first parameter is empty
param #1 is -> 
param #2 is -> hello

$ testFunc "hey" "hello"
param #1 is -> hey
param #2 is -> hello
于 2013-10-15T08:43:11.413 回答
1

另一个最佳实践是检查使用 $# 传递的参数数量。

但是,这并不能解决一个空参数的问题,你怎么知道param1是空的还是param2是空的。因此,这两种支票都是好东西。

于 2013-10-15T08:53:24.853 回答
0

可以set -o nounset在正文中添加一个 bash 文件以达到与此相同的效果bash -u

#!/bin/bash
set -o nounset

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

param1="param1"
param2="param2"

testFunc $param1 $param2
于 2020-09-12T03:42:25.237 回答