0

I have a process I want to start from Java. The problem is that due to a mismatch between the remote desktop client and the process I want to start I need to modify the environment variables. I will not use this in production, but only for running tests. I will also just do this until this bug is fixed in the tool I use.

I do not have root access and I am using Linux RHEL7. Anyone having an idea how I can set this environment variable from Java? I should also add that I run this from an IDE.

The following answer was not very helpful due to the lack of actual examples: Is it possible to set an environment variable at runtime from Java?

and the following example was not able to set the variables in the scope I needed to set them: Java - set environment variable

I tried this,

Process p = Runtime.getRuntime().exec("setenv " + name + " " + value);

But get the following error message,

java.io.IOException: Cannot run program "setenv": error=2, No such file or directory

EDIT: Someone suggested this post,

How do I set environment variables from Java?

Unfortunately I do not find any solutions in there. The process I want to start already have a Java API, which does not work in my environment. What I want is an equivalent to the linux command,

setenv NAME VALUE

for the process which java runs in.

patrik
  • 4,506
  • 6
  • 24
  • 48
  • @randomir nope, this does not work. Or actually process builder would work if I hade time to rewrite a lot of code. – patrik Nov 02 '17 at 13:17
  • `setenv` is not a Linux command, and cannot be. It is a _shell_ (builtin) command in _some_ shells, notably csh and tcsh, on _all_ systems (not just Linux), but not other shells (even on Linux). It is also a system call, but system calls are not programs or commands. You don't identify your IDE, but in Eclipse you can set envvars in any run config, and you can have multiple run configs for one program; and I'd be astonished if other IDEs don't have similar, since this is a quite common thing to do. – dave_thompson_085 Nov 02 '17 at 14:37

1 Answers1

0

Use ProcessBuilder:

ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
 Map<String, String> env = pb.environment();
 env.put("VAR1", "myValue");
 env.remove("OTHERVAR");
 env.put("VAR2", env.get("VAR1") + "suffix");
 Process p = pb.start();
Morad
  • 2,761
  • 21
  • 29
  • Ok so this basically means I have to add these arguments to the specific process I wish to start? This would in practice work, but it would be a great deal of trouble. The reason for this is that we already have an API for the process I want to start. So basically I just want to set a baseline parameter set which can be used for any process. I know this is not a safe way to do things, but for a private 20 line (ish) test case I do not think it matter that much. – patrik Nov 02 '17 at 13:01