How to pass a null parameter to a function

How to pass a null parameter to a function

am 28.01.2008 09:42:17 von Wenhua Zhao

Hi,

In the follow,
--
ARGS="arg1 arg2"

function foo() {
echo $1
echo $2
}
--

I want ``arg1'' to be a null string. How should I set the variable
$ARGS??

Thanks a lot.
Wenhua

Re: How to pass a null parameter to a function

am 28.01.2008 11:24:38 von Stephane CHAZELAS

On Mon, 28 Jan 2008 00:42:17 -0800 (PST), whzhao@gmail.com wrote:
> Hi,
>
> In the follow,
> --
> ARGS="arg1 arg2"
>
> function foo() {

Please avoid that syntax.

Either use the sh way:

foo() {
}

or the ksh way:

function foo {
}

but don't mix both.

> echo $1

echo "$1"

> echo $2
> }
> --
>
> I want ``arg1'' to be a null string. How should I set the variable
> $ARGS??
[...]

IFS=,
set -f # remember you almost always need to disable filename
# generation if you leave a variable expansion unquoted
ARGS=",arg2"

foo $ARGS

Or if you want to write a bash/ksh/zsh script instead of a sh
one:

args=("" arg2)
foo "${args[@]}"

You could also do (which may be closer to what you actually
want):

args='"" arg2'
eval "foo $args"

It makes it easy to extend that to arguments that contain IFS
characters.

args='"arg 1" "arg,2" ""'
eval "foo $args"

Of course, you have to beware that it may be dangerous if you
don't have control on the value of $args as in:

args='; rm -rf "${HOME:-/}"'

--
Stephane