简体   繁体   中英

Bash - export environment variables with special characters ($)

I'm parsing a file with key=value data and then export them as environment variables. My solution works, but not with special characters, example:

.data

VAR1=abc
VAR2=d#r3_P{os-!kblg1$we3d4xhshq7=mf$@6@3l^

script.sh

#!/bin/bash
while IFS="=" read -r key value; do
  case "$key" in
    '#'*) ;;
    *)
      eval "$key=\"$value\""
      export $key
  esac
done < .data

$ . ./script.sh

Output:

$ echo $VAR1
abc
$ echo $VAR2
d#r3_P{os-!kblg1=mf6@3l^

but should be: d#r3_P{os-!kblg1$we3d4xhshq7=mf$@6@3l^

只需用反斜杠 \\ 转义 $ 符号

只需使用单引号:

export VAR2='d#r3_P{os-!kblg1$we3d4xhshq7=mf$@6@3l^'

You don't need eval at all, just use declare built-in in bash to create variables on-the-fly!

case "$key" in
  '#'*) ;;
   *)
       declare $key=$value
       export "$key"
esac

If you cannot change the .data file you have to escape the special character $ when assigning the value to key. Change the assignment line to:

eval "$key=\"${value//\$/\\\$}\""

${variable//A/B} means substituting every instance of A to B in variable .

More useful info on bash variables here

I found the following script (to be sourced) helpful:

set -a
source <(cat development.env | \
    sed -e '/^#/d;/^\s*$/d' -e "s/'/'\\\''/g" -e "s/=\(.*\)/='\1'/g")
set +a

From: https://stackoverflow.com/a/66118031/339144

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