Retrieve value of PATH environment variable on Linux using Java

Question:

I didn't find a good topic on this subject and decided to create this question, for those who are experiencing this problem. Using System.getenv("PATH") does not list all the values ​​of that environment variable. Tested points:

  • Running the echo $PATH command in the linux terminal correctly lists all configured paths.
  • Turning off the machine does not work
  • ProcessEnvironment.environment() returns the same thing as the first code

I'm using this code:

String[] cmd = ['echo', '$PATH']
Process p = Runtime.getRuntime().exec(cmd);

BufferedReader retorno = new BufferedReader(new InputStreamReader(p.getInputStream()))
retorno.readLines()

Theoretically it should return the same value as in the terminal, but in addition to not identifying some programs like 'help', when using echo $PATH the return is an array of size 1 with the value $PATH in string.

Anyone with an interesting solution to this problem?

Answer:

try like this

System.out.println(System.getenv("PATH"));
Scroll to Top