Tenzin
Tenzin

Reputation: 2505

Putting output into a variable

I am trying to make a batch file that sets the JAVA_HOME.

Now I have the following code that looks for if a path exists. If that is the case I would like to store the complete name in a variable.

set javaLoc=
set javaLoc=$(dir "C:\Program Files (x86)\Java\jre1.8*" /s/b) 
echo %javaLoc% 

But the echo returns me:

$(dir "C:\Program Files (x86)\Java\jre1.8*" /s/b) 

While I would like to capture the output (C:\Program Files (x86)\Java\jre1.8.0_40) from it in "javaLoc".

I also tried:

dir "C:\Program Files (x86)\Java\jre1.8*" /s/b > javaLoc

But also that doesn't work.
Can anyone help me on what I am doing wrong?

Upvotes: 1

Views: 43

Answers (1)

SomethingDark
SomethingDark

Reputation: 14304

I see you're coming in with experience from bash (or possibly kornshell). Sadly, batch is a bit more limited than it's *nix counterpart, so you can't directly store the output of a command in a variable.

You can, however, run the command through a for /F loop and store the result in a variable that way, like this:

for /F %%A in ('dir "C:\Program Files (x86)\Java\jre1.8*" /s /b') do (
    set javaLoc=%%A
)

Although it should be noted that if there is more than one item returned by this command, javaLoc will be set to the last one in the list.

Upvotes: 1

Related Questions