On 2012-01-26, Harry Putnam wrote:
> I'm having a time here just trying to test/print the number of command
> line arguments.
>
> Running: GNU bash, version 4.2.20(1)-release (i486-pc-linux-gnu)
>
> I know that value can be accessed in the same way as any array but am
> not getting the syntax right. Googling has produced a large pile of
> hits and many things about showing the count of array elements and
> about `$@' the command line array. But again not finding the exact
> syntax.
>
> bash script `scr.bash'
> ------- 8< snip ---------- 8< snip ---------- 8<snip -------
> #!/usr/local/bin/bash
>
> array=( one two three)
>
> echo ' This array:
> array=( one two three)
> has: < '${#array[@]} " > elements
> ------- ------- ---=--- ------- -------
> "
>
> echo "my command line has < ${#[@]} > elements"
The number of arguments is $#
> echo "------- ------- ---=--- ------- -------
> "
> echo "My command line is <$*>"
> ------- --------- ---=--- --------- --------
> Call it like: `scr now what':
> Output:
> ,----
>| This array:
>| array=( one two three)
>| has: < 3 > elements
>| ------- ------- ---=--- ------- -------
>|
>| ./scr: line 11: my command line has < ${#[@]} > elements: bad substitution
$# is not an array variable.
>| ------- ------- ---=--- ------- -------
>|
>| My command line is <now what>
> `----
> NOT
> ------- --------- ---=--- --------- --------
> Changed to: ${#$[@]}
>
> (same output)
>
> NOT
> ------- --------- ---=--- --------- --------
>
> Changed to ${$#[@]}
That is the same as ${$}; # tells it to remove a leading @ (if
there is one).
> Output:
>
> ,----
>| This array:
>| array=( one two three)
>| has: < 3 > elements
>| ------- ------- ---=--- ------- -------
>|
>| my command line has < 11171 > elements
>| ------- ------- ---=--- ------- -------
>|
>| My command line is <now what>
> `----
>
> What does that number (11171) mean?
Try: echo $$
> NOT
> ------- --------- ---=--- --------- --------
>
> Finally in desperation I changed it to a simple `$#'
As it should be!
> Output:
>
> ,----
>| This array:
>| array=( one two three)
>| has: < 3 > elements
>| ------- ------- ---=--- ------- -------
>|
>| my command line has < 2 > elements
>| ------- ------- ---=--- ------- -------
>|
>| My command line is <now what>
> `----
> YIPPEE
> Egad, that appears to be what I'm after. But is that really the way?
Yes. $# is the number of arguments.