Creating a string variable name from the value of another string

前端 未结 3 901
花落未央
花落未央 2020-11-28 12:11

In my bash script I have two variables CONFIG_OPTION and CONFIG_VALUE which contain string VENDOR_NAME and Default_Vendor

3条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-28 12:44

    For pure shell, possibly try:

    #!/usr/bin/env sh
    
    option=vendor_name
    value="my vendor"
    
    eval $option="'$value'" # be careful with ', \n, and \ in value
    eval echo "\$$option" # my vendor
    echo "$vendor_name" # my vendor
    

    Why?

    #!/usr/bin/env sh
    printf -v "var" "val" # prints the flag, var not set
    declare var=val # sh: declare: not found
    echo ${!var} # sh: syntax error: bad substitution
    

    I don't like eval, but are there any POSIX options?

提交回复
热议问题