Reference to a bash variable whose name contains dot

后端 未结 5 1819
盖世英雄少女心
盖世英雄少女心 2020-12-06 05:36

I have a bash variable: agent1.ip with 192.168.100.137 as its value. When I refer to it in echo like this:

echo $agent         


        
相关标签:
5条回答
  • 2020-12-06 06:14

    Since bash.ip is not a valid identifier in bash, the environment string bash.ip=192.168.100.37 is not used to create a shell variable on shell startup.

    I would use awk, a standard tool, to extract the value from the environment.

    bash_ip=$(awk 'BEGIN {print ENVIRON["bash.ip"]}')
    
    0 讨论(0)
  • 2020-12-06 06:14

    Is your code nested, and using functions or scripts that use ksh?

    Dotted variable names are an advanced feature in ksh93. A simple case is

    $ a=1
    $ a.b=123
    $ echo ${a.b}
    123
    $ echo $a
    1
    

    If you first attempt to assign to a.b, you'll get

     -ksh: a.b=123: no parent
    

    IHTH

    0 讨论(0)
  • 2020-12-06 06:23

    Bash itself doesn't understand variable names with dots in them, but that doesn't mean you can't have such a variable in your environment. Here's an example of how to set it and get it all in one:

    env 'agent1.ip=192.168.100.137' bash -c 'env | grep ^agent1\\.ip= | cut -d= -f2-'
    
    0 讨论(0)
  • 2020-12-06 06:24

    Try this:

    export myval=`env | grep agent1.port | awk -F'=' '{print $2}'`;echo $myval
    
    0 讨论(0)
  • 2020-12-06 06:33

    The cleanest solution is:

    echo path.data | awk '{print ENVIRON[$1]}'
    
    0 讨论(0)
提交回复
热议问题