Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Linux environment variable programmatically in Java

Tags:

java

linux

I am able to run a Linux command via RunTime class. Is there a way of setting a Linux global enviroment from Java programatically?

I want to emulate the following Linux command statement over Java

root@machine:/tmp# export TEST=v2

I have used ProcessBuilder as following, but TEST variable does not changed.

ProcessBuilder pb = new ProcessBuilder("/bin/bash","-c","export TEST=v3" + "&& exec");

UPDATE: Actually my ultimate target is to use EMAIL_NAME enviroment as an email address, when both my application and machine are started and stopeed these actions will be sent to EMAIL_NAME. In that case I understand that it is not possible to set linux global enviroment over pure Java code. So I have a workaround solution is that EMAIL_NAME will be hold in a file and it will be updated or read by linux script or java code.

like image 936
Ahmet Karakaya Avatar asked Dec 24 '12 14:12

Ahmet Karakaya


1 Answers

Environment variables, when set, are only available to processes spawned by the process where the variable is set, so if you're really asking to set a variable that will affect the entire system, then no. You can't really do that at all in Linux interactively. The best you could do is alter one of the system startup files to include said variable so that anything you do in the future would include that variable.

If you're simply looking to run several processes with some variable set, then ProcessBuilder allows you to set an environment for processes spawned with it. Reusing an environment for several processes is pretty trivial with that.

like image 71
Ryan Stewart Avatar answered Oct 05 '22 07:10

Ryan Stewart