This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes echo <Environment Variable> Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "echo <Environment Variable>" Watch "echo <Environment Variable>" New topic

echo <Environment Variable>

SachinP Kale

Joined: Aug 16, 2011
Posts: 2

I want to run the command using java code

echo $PATH

I used Runtime.getRuntime().exec() for this, but it returns outputp as : $PATH.

I know I can get the value of PATH variable using System.getProperty() but I want to use particularly "echo" command.

How can I do it?
N Sahni
Ranch Hand

Joined: Jul 07, 2011
Posts: 55


You can try this it worked for me in windows environment:

May be for Unix environment you might have to use "sh" instead of "cmd.exe".

Thanks and Regards,
Nilesh Sahni | |
Rob Spoor

Joined: Oct 27, 2005
Posts: 20192

Welcome to the Ranch!

$PATH is resolved by the shell, so you'll need to execute this command using a shell: sh -c $PATH. If you're using Windows, the command should be cmd /C echo %PATH%. Note that Windows uses %PATH% instead of $PATH.

Edit: basically what N Sahni said
There is just one flaw in that code: the error stream should also be read. See When Runtime.exec() won't. In this case the solution is simple: add process.redirectErrorStream(true); before line 7.

How To Ask Questions How To Answer Questions
SachinP Kale

Joined: Aug 16, 2011
Posts: 2
Yes, that worked.

But, one question.

As you are redirecting errorStream here, it means it shows as error if we run "sh -c $PATH", right?

when I run "echo \$PATH" on shell, it gives me output as: $PATH.
Doesn't it mean that Java automatically adds "\" before "$" sign as Runtime.getRuntime().exec("echo $PATH") also gives me the same output?

Thanks for the help.
wood burning stoves
subject: echo <Environment Variable>
jQuery in Action, 3rd edition