Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

echo <Environment Variable>

 
SachinP Kale
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi,

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
Posts: 55
Java Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

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".
 
Rob Spoor
Sheriff
Pie
Posts: 20527
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
SachinP Kale
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?

Also,
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic