2

I have to use/reference an environment variable value which will be passed as a command line argument. Something like below

set myvar=%1
echo Value of %myvar% is %%myvar%%

Here in %%myvar%% I want to reference the value of that environment varible

A typical call to this script will be

script.bat JAVA_HOME
Tushar Joshi
  • 131
  • 5
  • Since it's environment variable, why it must be passed as a command line parameter in the first place? Why can't the script use environment variables directly? – Esa Jokinen Mar 09 '15 at 10:00
  • @EsaJokinen I need to create some scripts which will test whether certain environment variables exists before I start some tasks. Like before working with Java I want a script to check whether JAVA_HOME, ANT_HOME, M2_HOME is already set. In another language I may need some other environmental variables checked. I want to create a utility script which will check any given variable and to use that utility in other scripts – Tushar Joshi Mar 10 '15 at 11:35

1 Answers1

3

You don't need the intermediate myvar variable. If you want it, then simply substitute %myvar% for %1 below.

You need two rounds of expansion.

Option 1 - CALL

@echo off
call echo %%%1%%

In the first parsing phase

  • %% expands to %
  • %1 expands to JAVA_HOME
  • %% expands to %

In the CALL phase, %JAVA_HOME% expands to the value you are looking for.

Option 2 - Delayed Expansion

@echo off
setlocal enableDelayedExpansion
echo !%1!

The delayed expansion form is much easier to read


See How does the Windows Command Interpreter (CMD.EXE) parse scripts? for more info

dbenham
  • 651
  • 4
  • 12