Creating a string variable name from the value of another string

前端 未结 3 900
花落未央
花落未央 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:24

    This uses bash builtins:

    #!/bin/bash
    
    VAR1="VAR2"
    
    declare "${VAR1}"="value"
    
    echo "VAR1=${VAR1}"
    echo "VAR2=${VAR2}"
    

    The script output:

    VAR1=VAR2
    VAR2=value
    

    Here's the snippet using your variable names:

    #!/bin/bash
    
    CONFIG_OPTION="VENDOR_NAME"
    
    declare "${CONFIG_OPTION}"="value"
    
    echo "CONFIG_OPTION=${CONFIG_OPTION}"
    echo "VENDOR_NAME=${VENDOR_NAME}"
    

    The script output:

    CONFIG_OPTION=VENDOR_NAME
    VENDOR_NAME=value
    
    0 讨论(0)
  • 2020-11-28 12:31

    I know that nobody will mention it, so here I go. You can use printf!

    #!/bin/bash
    
    CONFIG_OPTION="VENDOR_NAME"
    CONFIG_VALUE="Default_Vendor"
    
    printf -v "$CONFIG_OPTION" "%s" "$CONFIG_VALUE"
    
    # Don't believe me?
    echo "$VENDOR_NAME"
    
    0 讨论(0)
  • 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?

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