Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.getenv doesn't get variables defined in ~/.bash_profile

Tags:

java

linux

bash

Here is a line in file ~/.bash_profile

export MESSAGE="Hello World"

I want to access system variable MESSAGE in java.

System.getenv("MESSAGE"); doesn't work.

like image 601
Patrick Lorio Avatar asked Sep 06 '12 16:09

Patrick Lorio


Video Answer


2 Answers

The .bash_profile file is only sourced for login shells. If your java process is spawned from a shell that is not a login shell (for example a script with a #!/bin/sh at the top) then it will not read it (though it may still inherit MESSAGE from the environment depending on how you run it).

Note also that .bash_profile is also not run for interactive shells that are not "login" shells, so you can't rely on it being run even when you have a shell prompt. People usually use .bashrc, which is sourced for all interactive shells, for that purpose.

If you want a variable to be set in all Bourne shell derivatives regardless of whether they are interactive or not, put it in both .profile and .bashrc.

like image 124
Andy Ross Avatar answered Oct 17 '22 08:10

Andy Ross


I would recommend you to test if your environment variable is indeed "defined" by using echo $MESSAGE as suggested above.
In addition, changing the bash_profile file will not effect your current shell,
you must use "source" in order for it to effect your current shell.
I would also recommend reading this article about differences between bashrc and bash_profile.
Maybe you should define the EXPORT at bashrc?

like image 41
Yair Zaslavsky Avatar answered Oct 17 '22 06:10

Yair Zaslavsky