简体   繁体   中英

Exclamation mark and hash within curly braces in bash

I'm trying to understand a bash script and I'm having trouble with the following line:

result=${!#}

I found part of the solution ( ! within ${} ) here :

If the first character of parameter is an exclamation point (!), it introduces a level of variable indirection. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion.

Another part of the solution ( # within ${} ) is here :

The length in characters of the expanded value of parameter is substituted. If parameter is ' ' or '@', the value substituted is the number of positional parameters. If parameter is an array name subscripted by ' ' or '@', the value substituted is the number of elements in the array. If parameter is an indexed array name subscripted by a negative number, that number is interpreted as relative to one greater than the maximum index of parameter, so negative indices count back from the end of the array, and an index of -1 references the last element.

But I don't know how these two are combined into result . What does this line do?

${#} is the number of arguments in the current shell/function:

$ set -- a b c
$ echo ${#}
3

The ! performs indirect parameter expansion, so the value of ${#} is used as the name of the parameter to expand.

$ echo ${!#}  # same as echo ${3}
c

In short, ${!#} expands to the value of the last argument.


In the absence of such bash extensions, one might simply write a loop like

for result; do :; done  # instead of result=${!#}

which would iterate over the positional arguments, setting result to each in turn, leaving result with the value of the last one once the loop completes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM