User:Midnite/Notes/Shell Script/Variable argument count needs eval

From Gentoo Wiki
Jump to:navigation Jump to:search

If variable argument count (i.e. $#) is needed, use of eval is needed.

CODE If variable argument count (i.e. $#) is needed, use of eval is needed.
#!/bin/sh

func() {
	printf '%d func args:' $#
	printf ' [%s]' "$@"
	printf '\n'
}

var1='one'
blank=''
unset nil
var2='two'

printf '=== 01) Non blank args have no problems ===\n'
func "$( printf '%s' "$var1" )" "$( printf -- '--%s' "$var2" )" --"$( printf '%s' "$var1" )"

printf '=== 02) Blank and unset args will still be passed ===\n'
func "$( printf '%s' "$blank" )" "$( printf '%s' "$nil" )" "$( printf -- '--%s' "$nil" )" "$( printf '%s' "$var1" )"

printf '=== 03) Even non-printed args will be passed as blank args ===\n'
                                                                   # test isset nil
func "$( { [ -n "$blank" ] && printf '%s' "$blank" ;} ||: )" "$( { [ -n "${nil+x}" ] && printf -- '--%s' "$nil" ;} ||: )" "$( printf '%s' "$var2" )"

printf '=== 04) If change of $# is needed, '"\`"'eval'"\`"' is needed. ===\n'
                                            # test isset nil
eval func "$( printf '%s' "$blank" )" "$( { [ -n "${nil+x}" ] && printf -- '--%s' "$nil" ;} ||: )" "$( printf '%s' "$var2" )"

Output:

=== 01) Non blank args have no problems ===
3 func args: [one] [--two] [--one]
=== 02) Blank and unset args will still be passed ===
4 func args: [] [] [--] [one]
=== 03) Even non-printed args will be passed as blank args ===
3 func args: [] [] [two]
=== 04) If change of $# is needed, `eval` is needed. ===
1 func args: [two]