3

Within a Java 1.8 program, how can I execute a program on the user's PATH? For simplicity let's assume that only *nix systems have to be supported. What I want to do is something like:

Runtime.getRuntime().exec("myProgram")

where myProgram is somewhere on the user's PATH.

Runtime.getRuntime().exec(cmd) can only "see" programs on the system's path. For example in my case (mac os) /usr/bin:/bin:/usr/sbin:/sbin, but what if myProgram is in /usr/local/bin or ~/bin?

I tried to get the directories on the user's PATH by parsing the output of Runtime.getRuntime().exec("echo $PATH"), but I get back only the string "$PATH" itself, not the actual content of the PATH variable.

EDIT Executing System.getenv() gives me only PATH=/usr/bin:/bin:/usr/sbin:/sbin, i.e. not the user's PATH.

2 Answers 2

1

If you want to get the actual content of the PATH variable you can use:

System.getenv():

Good luck!

Sign up to request clarification or add additional context in comments.

5 Comments

I'm not sure what you mean by user's path could you please clarify? path to my knowledge is the default path where when you execute something it automatically looks... do you mean something else? thanks
I mean the content of the PATH variable of the user running the Java program. I.e. what you would see by executing from the shell echo $PATH. In any case, my actual problem is how to run a program that is on the PATH, but I don't know exactly where, e.g. in ~/bin or in /usr/local/bin.
how about - System.getProperty("user.home") or System.getProperty("user.dir")
Not really, that would give me only the home dir and current dir. Not the list of paths where the program could be (.e.g /usr/local/bin or wherever the user decides to put it on his/her PATH)
but the user directory would be the actual place the program is running. isn't that what you want?
0

String userPath = System.getenv("PATH");

If it returns a null string then try exporting that $PATH variable before running your java program.

2 Comments

It doesn't return null, it returns only "/usr/bin:/bin:/usr/sbin:/sbin" whereas "echo $PATH" returns a lot more stuff, including for example /usr/local/bin.
Maybe you are running java program from different shell. Try echo $PATH from same shell from where you are running java program. It should be same. Try Echo $PATH in preferable in same script which is running java program.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.