#774001 ${#@} and ${#*} are incompatable with bash and posh

Package:
dash
Source:
dash
Description:
POSIX-compliant shell
Submitter:
Joey Hess
Date:
2015-08-16 13:45:21 UTC
Severity:
normal
#774001#5
Date:
2014-12-26 23:30:52 UTC
From:
To:
joey@darkstar:~>cat testcase
#!/bin/sh
echo ${#@}

joey@darkstar:~>bash testcase a
1
joey@darkstar:~>posh testcase a
1
joey@darkstar:~>dash testcase a
1

good so far...

joey@darkstar:~>bash testcase a b
2
joey@darkstar:~>posh testcase a b
2
joey@darkstar:~>dash testcase a b
3

!!

joey@darkstar:~>bash testcase a b c
3
joey@darkstar:~>posh testcase a b c
3
joey@darkstar:~>dash testcase a b c
5

joey@darkstar:~>bash testcase aaa bbb cccc
3
joey@darkstar:~>posh testcase aaa bbb cccc
3
joey@darkstar:~>dash testcase aaa bbb cccc
12


posh:
       ${#name}
           The number of positional parameters if name is *, @ or is
           not specified, or the length of the string value of
           parameter name.

bash:

	${#name[subscript]}  expands  to  the  length  of  ${name[sub‐
       script]}.  If subscript is * or @, the expansion is the number
       of elements in the array.

dash:

     ${#parameter}         String Length.  The length in characters
                           of the value of parameter.

So dash's documentation doesn't specify what it does for ${#@}. What its
actually doing is taking the length of the string consisting of all the
positional parameters, separated by spaces.

I have not checked if the behavior of ${#@} is standardized in any way.
If ${#@} is standardized, then dash should follow the standard.

Currently, a #!/bin/sh script cannot currently safely use ${#@}, because
/bin/sh can be dash or bash. If some package contains a #!/bin/dash
script, it could rely on the current behavior. OTOH, the behavior is
undocumented, and seems pretty useless, so it's unlikely someone would
go to the bother of using #!/bin/dash to get it. This might argue for
changing the behavior to match bash and posh even if there is not a
standard.

On the other hand, $# reliably yields the number of positional parameters
in all of bash, posh, and dash. So any script can use that. So, the easiest
fix would be to just document on its man page the special way bash handles
${#@} (and ${#*})

#774001#8
Date:
2015-08-16 13:33:40 UTC
From:
To:
description of ${#parameter} further on explicitly documents what ${#@}
and ${#*} expand to, the same as $#.

This is actually the length of the expansion of $@ or $* in a context
where word splitting is not performed, except if IFS is set to the empty
string.

POSIX leaves the result of the expansion of ${#@} and ${#*} unspecified.

Dash's ${#*} may be a faster alternative to temp="$*"; ${#temp}.
However, the silently inconsistent behaviour across shells is a good
reason not to use it.

Indeed, there is no reason to use ${#@} and ${#*} in bash/posh.