How to get value of environment variable from passed command line parameter

Posted on

How to get value of environment variable from passed command line parameter – Managing your servers can streamline the performance of your team by allowing them to complete complex tasks faster. Plus, it can enable them to detect problems early on before they get out of hand and compromise your business. As a result, the risk of experiencing operational setbacks is drastically lower.

But the only way to make the most of your server management is to perform it correctly. And to help you do so, this article will share nine tips on improving your server management and fix some problem about windows, scripting, batch, , .

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

Solution :

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

Leave a Reply

Your email address will not be published.