Ubuntu – What does $# mean in bash

bash

I have a script in a file named instance:

echo "hello world"
echo ${1}

And when I run this script using:

./instance solfish

I get this output:

hello world
solfish

But when I run:

echo $# 

It says "0". Why? I don't understand what $# means.

Please explain it.

Best Answer

$# is a special variable in bash, that expands to the number of arguments (positional parameters) i.e. $1, $2 ... passed to the script in question or the shell in case of argument directly passed to the shell e.g. in bash -c '...' .....

This is similar to argc in C.


Perhaps this will make it clear:

$ bash -c 'echo $#'
0

$ bash -c 'echo $#' _ x
1

$ bash -c 'echo $#' _ x y
2

$ bash -c 'echo $#' _ x y z
3

Note that, bash -c takes argument after the command following it starting from 0 ($0; technically, it's just bash's way of letting you set $0, not an argument really), so _ is used here just as a placeholder; actual arguments are x ($1), y ($2), and z ($3).


Similarly, in your script (assuming script.sh) if you have:

#!/usr/bin/env bash
echo "$#"

Then when you do:

./script.sh foo bar

the script will output 2; likewise,

./script.sh foo

will output 1.