Bash – How does ${!#} work in bash to get the last command-line argument

bash

From the Advanced Bash-Scripting Guide, to get the last command-line argument:

Or: lastarg=${!#}
This is an
indirect reference to the $# variable.
Note that lastarg=${!$#} doesn't work.

Best Answer

As it says it is an indirect reference. Take the following example:

$ var=test
$ test='Hello, world'
$ echo ${!var}
Hello, world

Now if I were to set the following positional parameters:

$ set -- one two three

And $# will represent the total number of positional parameters:

$ echo $#
3

This means when I call it like ${!#} I'm saying give me the value of the parameter named 3:

$ echo ${!#}
three