Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem of empty variable using set in Windows Batch

Tags:

batch-file

set var=%1
echo var
set command=""
IF var==true ( 
    set command=dir
)

IF var==false ( 
    set command=dir /a
)
echo %command%
%command%

So, if I run this script by typing in

C:\>test true

the echo %command% always prints "". Any idea?

like image 556
zs2020 Avatar asked Jun 24 '11 20:06

zs2020


People also ask

What does set do in batch?

When creating batch files, you can use set to create variables, and then use them in the same way that you would use the numbered variables %0 through %9. You can also use the variables %0 through %9 as input for set. If you call a variable value from a batch file, enclose the value with percent signs (%).

What does 0 |% 0 Do in batch?

What does 0 |% 0 Do in batch? %0|%0 is a fork bomb. It will spawn another process using a pipe | which runs a copy of the same program asynchronously. This hogs the CPU and memory, slowing down the system to a near-halt (or even crash the system).

What is set P in batch file?

The /P switch allows you to set a variable equal to a line of input entered by the user. The Prompt string is displayed before the user input is read.

What is @echo in batch file?

To display the command prompt again, type echo on. To prevent all commands in a batch file (including the echo off command) from displaying on the screen, on the first line of the batch file type: Copy.


1 Answers

You are missing some % signs that are needed for any variable dereferencing.

You probably want it like this:

set var=%1
echo %var%
set command=""
IF %var%==true (                    <=== here
    set command=dir
)

IF %var%==false (                   <=== here
    set command=dir /a
)
echo %command%
%command%

You should also surround your string comparisons with quotes to allow for spaces, something like this:

IF "%var%"=="false"

Also, as Joey pointed out, clearing a variable is done by

set command=

without any quotes. Otherwise you will initialize the the variable with these quotes, leading to your weird output.

like image 57
Frank Bollack Avatar answered Oct 09 '22 12:10

Frank Bollack