Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash - export environment variables with special characters ($)

Tags:

bash

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^

like image 549
User Avatar asked Apr 19 '17 12:04

User


People also ask

How do you escape special characters in variable Bash?

Except within single quotes, characters with special meanings in Bash have to be escaped to preserve their literal values. In practice, this is mainly done with the escape character \ <backslash>.

How do I export an environment variable in Bash?

The easiest way to set environment variables in Bash is to use the “export” keyword followed by the variable name, an equal sign and the value to be assigned to the environment variable.

How do I add special characters to a Bash script?

In a shell, the most common way to escape special characters is to use a backslash before the characters. These special characters include characters like ?, +, $, !, and [. The other characters like ?, !, and $ have special meaning in the shell as well.


4 Answers

Just escape the $ sign with backslash \

like image 154
Yedidia Avatar answered Oct 20 '22 07:10

Yedidia


Just use single quotes:

export VAR2='d#r3_P{os-!kblg1$we3d4xhshq7=mf$@6@3l^'
like image 33
Bernardo Ramos Avatar answered Oct 20 '22 06:10

Bernardo Ramos


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
like image 44
Inian Avatar answered Oct 20 '22 08:10

Inian


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

like image 26
Klaas van Schelven Avatar answered Oct 20 '22 07:10

Klaas van Schelven