Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
462 views
in Technique[技术] by (71.8m points)

parameter passing - Pass empty variable in bash

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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"

So to pass an empty variable you say:

testFunct "" "$param2"

See an example:

Given this function:

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...