user3475234
user3475234

Reputation: 1573

UNIX - why doesn't $# include the command (thus always being >= 1)?

It's kind of hard to search for an answer on this since $# doesn't seem to go through properly on search engines. I was curious as to why argv typically includes the command name itself, while $# doesn't.

To make it clearer, if I have a script called testing.sh

#!/bin/bash
echo $#

./testing.sh returns 0 and not 1. Why?

Upvotes: 1

Views: 54

Answers (1)

chepner
chepner

Reputation: 530940

bash is following the POSIX specification for $#:

Expands to the decimal number of positional parameters. The command name (parameter 0) shall not be counted in the number given by '#' because it is a special parameter, not a positional parameter.

The shell's interface to the arguments is simply different from C's. In bash terms, you might define

argv=( "$0" "$@")
argc=${#argv[@]}

since the shell (sensibly) separates the command name from the command's arguments.

Upvotes: 5

Related Questions