Using a variable to refer to another variable in Bash

前端 未结 3 939
青春惊慌失措
青春惊慌失措 2020-12-01 13:58
x=1
c1=string1
c2=string2
c3=string3

echo $c1
string1

I\'d like to have the output be string1 by using something like: echo $(c

相关标签:
3条回答
  • 2020-12-01 14:35

    if you have bash 4.0, you can use associative arrays.. Or you can just use arrays. Another tool you can use is awk

    eg

    awk 'BEGIN{
      c[1]="string1"
      c[2]="string2"
      c[3]="string3"
      for(x=1;x<=3;x++){
        print c[x]
      }
    }'
    
    0 讨论(0)
  • 2020-12-01 14:50

    See the Bash FAQ: How can I use variable variables (indirect variables, pointers, references) or associative arrays?

    To quote their example:

    realvariable=contents
    ref=realvariable
    echo "${!ref}"   # prints the contents of the real variable
    

    To show how this is useful for your example:

    get_c() { local tmp; tmp="c$x"; printf %s "${!tmp}"; }
    x=1
    c1=string1
    c2=string2
    c3=string3
    echo "$(get_c)"
    

    If, of course, you want to do it the Right Way and just use an array:

    c=( "string1" "string2" "string3" )
    x=1
    echo "${c[$x]}"
    

    Note that these arrays are zero-indexed, so with x=1 it prints string2; if you want string1, you'll need x=0.

    0 讨论(0)
  • 2020-12-01 14:52

    Try this:

    eval echo \$c$x
    

    Like others said, it makes more sense to use array in this case.

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