cancel
Showing results for 
Search instead for 
Did you mean: 

Functions parameters

Leo The Cat
Regular Advisor

Functions parameters

Hi

My function below must return $2 if $1 is null.

nvl() {

if [[ $1 == "" ]]; then
return $2
else
return $1
fi

}

echo $(nvl $test "null")


What is the correct syntax ?

Bests Regards
Den
2 REPLIES
Steven Schweda
Honored Contributor

Re: Functions parameters

> What is the correct syntax ?

It depends on exactly what you're trying to
do. Are you looking for something like this?

bash$ nvl() {
> if [ -z "$1" ]; then
> return "$2";
> else
> return "$1";
> fi
> }

bash$ nvl 23 34 45
bash$ echo $?
23

bash$ nvl '' 45 56
bash$ echo $?
45

Is there some actual problem which you are
trying to solve? Asking how to implement
some particular (bad) solution to a problem
may not be the best way to get a good
solution to that problem.
Heironimus
Honored Contributor

Re: Functions parameters

If you want the function to match how you're using it you need to echo instead of return.