What is indirect expansion? What does ${!var*} mean?

前端 未结 5 1437
野趣味
野趣味 2020-11-22 05:28

I\'m reading \"Bash Guide for Beginners\". It says:

If the first character of PARAMETER is an exclamation point, Bash uses the

相关标签:
5条回答
  • 2020-11-22 06:02

    There appears to be an exception when the given "indirection" ends in a *, as it does here. In this case, it gives all variable names that start with the part you specified (N here). Bash can do that because it tracks variables and knows which ones exist.

    True indirection is this:
    Say I have a variable $VARIABLE set to 42, and I have another variable $NAME set to VARIABLE. ${!NAME} will give me 42. You use the value of one variable to tell you the name of another:

    $ NAME="VARIABLE"
    $ VARIABLE=42
    $ echo ${!NAME}
    42
    
    0 讨论(0)
  • 2020-11-22 06:08

    If you read the bash man page, it basically confirms what you have stated:

    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.

    However, reading on from there:

    The exceptions to this are the expansions of ${!prefix*} and ${!name[@]} described below.

    ${!prefix*} Names matching prefix. Expands to the names of variables whose names begin with prefix, separated by the first character of the IFS special variable.

    In other words, your particular example ${!N*} is an exception to the rule you quoted. It does, however, work as advertised in the expected cases, such as:

    $ export xyzzy=plugh ; export plugh=cave
    
    $ echo ${xyzzy}  # normal, xyzzy to plugh
    plugh
    
    $ echo ${!xyzzy} # indirection, xyzzy to plugh to cave
    cave
    
    0 讨论(0)
  • 2020-11-22 06:18

    You've hit an exception in indirection processing, where if the last character is *, all variables that have the prefix given before will be returned.

    0 讨论(0)
  • 2020-11-22 06:19

    Yes, it searches for all possible expansions of variables after the !. If you had done:

    echo ${!NP*}
    

    you would get only NPX_PLUGIN_PATH.

    Consider the following example:

    :~> export myVar="hi"
    :~> echo ${!my*}
        myVar
    :~> export ${!my*}="bye"
    :~> echo $myVar
        bye
    
    0 讨论(0)
  • 2020-11-22 06:19

    You can refer to this GNU doc for bash for authoritative information

    https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html#Shell-Parameter-Expansion

    But basically, indirect expansion is not performed on ${!prefix*} as one of the exceptions, in your example, N is the prefix.

    The Document will explain what indirect expansion is in bash

    0 讨论(0)
提交回复
热议问题