What does ${!i} do in bash? In that context, what is the effect of ((i+=1))?

前端 未结 2 565
孤街浪徒
孤街浪徒 2021-01-17 03:24

I do not find anything about the meaning of this:

case ${!i} in
     --fa)
       ((i+=1))
       fa=${!i}
       ;;

What is the meaning of

2条回答
  •  佛祖请我去吃肉
    2021-01-17 04:09

    ${!i} refers to the variable whose name is the value of $i. It is called variable indirection. See an example to make it more clear:

    $ i="hello"      # variable $i contains 'hello'
    $ hello="bye"    # variable $hello contains 'bye'
    $ echo "${!i}"   # when doing variable expansion of $i, it fetches $hello
    bye
    

    Regarding ((i+=1)), it is a way to increment the variable i. See:

    $ i=3
    $ ((i+=1))
    $ echo $i
    4
    

    You can also use either of these:

    i=$((i+1))
    
    ((i++))
    
    let "i=i+1"
    

    For further reference, see Bash Reference Manual - Shell Parameter Expansion:

    If the first character of parameter is an exclamation point (!), a level of variable indirection is introduced. 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

提交回复
热议问题