How can I get the variable value inside the EOF tags?

后端 未结 1 1511
半阙折子戏
半阙折子戏 2021-02-01 03:24

I have this following script, but I need to get $i variable value working inside that each block starting with EOF and ending with EOF.

It is not reading the variable val

相关标签:
1条回答
  • 2021-02-01 03:56

    Remove the backslash before EOF:

    #!/bin/bash
    
    i=ok
    
    # This prints "Bwah ok"
    cat <<EOF
    Bwah $i
    EOF
    
    # This prints "Bwah $i"
    cat <<\EOF
    Bwah $i
    EOF
    

    To get your last line display rightsubnet="10.109.0.20/32" (for i=1), you need something like this:

    i=1
    val1=beep
    val2=bop
    
    rightval="val$i"
    cat <<EOF
    This is a beep: ${!rightval}
    EOF
    

    That is, you compute the name of the variable you want, put that in another variable, and use the ${!var} syntax.

    But for that kind of thing you should rather use an array:

    i=0
    vals=(beep bop)
    
    cat <<EOF
    This is a beep: ${vals[$i]}
    EOF
    

    Note however that the indexes start at 0.

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