简体   繁体   中英

How to substitute bash variable concatenated with string?

I am trying to create a file myenv with following content SENDER_PASSWORD='my secret password'

BUILD_ENV=STAGING
STAGING_SENDER_PASSWORD="my secret password"

cat > myenv <<- EOL
SENDER_PASSWORD='${${BUILD_ENV}_SENDER_PASSWORD}'
EOL

bash: SENDER_PASSWORD='${${BUILD_ENV}_SENDER_PASSWORD}'
: bad substitution

Is there a way to achieve this with a single command? Basically I am trying to access the env variable STAGING_SENDER_PASSWORD and put it into myenv file

Is there a way to achieve this with a single command?

eval is your enemy:

SENDER_PASSWORD=$(eval echo \${${BUILD_ENV}_SENDER_PASSWORD})
// or better, with quoting
SENDER_PASSWORD=$(eval echo "\"\${${BUILD_ENV}_SENDER_PASSWORD}\"")

Using bash indirect variable expansion is way safer, but that would be two expressions:

SENDER_PASSWORD=$(tmp=${BUILD_ENV}_SENDER_PASSWORD; printf "%s" "${!tmp}")

Looking at your design aim, I would wrap that in a function (let's api it!):

get_var() {
    local tmp
    tmp=${BUILD_ENV}_$1
    # ex. add if [ -z "${!tmp}" ]; then use some default value
    printf "%s\n" "${!tmp}"
}

SENDER_PASSWORD=$(get_var SENDER_PASSWORD) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM