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.
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.
When you say "Linux global environment", do you mean Linux environment variable? If so, I think the answer is NO. Because it's not a java problem. When a process set environment var, it could only impact itself and its children process.
You can update the variable into /etc/profile through java
if(System.getProperty("TEST", "").equalsIgnoreCase(""))
{
Runtime.getRuntime().exec(new String[]{"bash","-c" ,"echo 'export TEST=v2' >> /etc/profile"}) ;
/// Also update the System Variable for current process
System.setProperty("TEST","v2") ;
}
And this will get effective from next login or if you do explicitly source it.
I use this line of code in the bash
echo -e PATH=\"/usr/lib/jvm/java-7-openjdk-i386/bin:\$PATH\" >> $HOME/.profile
with concatenates the path of the local user