1

So I have an environment variable in my .env file.

TESTMSG=abc$efg

And in rails console when I try to retrieve this data, it gets trimmed and the part after & doesn't get printed.

2.6.0 :001 > ENV['TESTWORD']
=> "abc"

How to get the complete word. I even tried puting quotes around the word like this.

TESTMSG="abc$efg"

which didn't work.

mechnicov
  • 12,025
  • 4
  • 33
  • 56
Nidhin S G
  • 1,685
  • 2
  • 15
  • 45
  • 1
    Are you using the dotenv gem? According to the [docs](https://github.com/bkeepers/dotenv#variable-substitution): _"If a value contains a `$` and it is not intended to be a variable, wrap it in single quotes."_ – Stefan Jul 07 '23 at 12:14
  • This likely follows bash rules, so yeah, what Stefan says. It's interpolating `$efg` as set here. – tadman Jul 07 '23 at 14:11
  • It is possible to escape with `\\` before special symbol – mechnicov Jul 07 '23 at 20:03

1 Answers1

2

Use the quotation marks when the string contains spaces or certain special character and certain syntaxes. because dollar sign (that is used to expand a variable – see below), .env files are, according to the page linked by you, regular bash scripts.

my_var=42
VARIABLES="foo ${my_var}"  # Gives “foo 42”.

Escape dollar sign in string by shell script (and .env also)

  • use \ before $
TESTMSG="abc\$efg" # or abc\$efg

3.0.2 :001 > ENV['TESTMSG']
 => "abc$efg" 

  • or just type it with single quotes
TESTMSG='abc$efg' 
3.0.2 :001 > ENV['TESTMSG']
 => "abc$efg"
Talaat Magdy
  • 199
  • 11