Recover value from PATH environment variable on Linux using Java

Asked

Viewed 233 times

3

I did not find a good topic on this subject and decided to create this question for those who are going through this problem. By using System.getenv("PATH") not listed all values of this environment variable. Tested points:

  • Run the linux terminal command echo $PATH correctly lists all configured paths.
  • Shutdown 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 the echo $PATH return is an array of size 1 with the value $PATH in string.

Someone with an interesting solution to this problem?

  • Have you ever tried something like String variavel = System.getenv("nome_da_variavel"); ?

  • Exactly at this point, behavior is not what you expect. echo $PATH will call the executable /bin/echo, not the shell builtin, and will also pass the string $PATH for the command. When typing in the terminal echo $PATH, who is invoked is builtin and, before invoking the command, the shell itself expands the variable and passes to the echo the content of PATH. The equivalent of what you tried to do in java would be /bin/echo '$PATH' (note the single quotes that prevent variable expansion)

1 answer

-1

Try it like this

System.out.println(System.getenv("PATH"));

Browser other questions tagged

You are not signed in. Login or sign up in order to post.