Windows Batch Files: if else

WindowsBatch File

Windows Problem Overview


I'm doing a simple batch file that requires one argument (you can provide more, but I ignore them).

For testing, this is what I have so far.

if not %1 == "" (
	dir /s/b %1
) else (
	echo no
)

Basically, I want to say if an argument is provided, recursively display all the files in the folder. Otherwise, say no.

It works when I provide an argument, but if I don't provide one it'll just tell me ( was unexpected at this time.

I mean, it works, but I wanted to at least display a user-friendly message explaining why it doesn't work. How should I change the code?

Windows Solutions


Solution 1 - Windows

if not %1 == "" (

must be

if not "%1" == "" (

If an argument isn't given, it's completely empty, not even "" (which represents an empty string in most programming languages). So we use the surrounding quotes to detect an empty argument.

Solution 2 - Windows

Surround your %1 with something.

Eg:

if not "%1" == ""

Another one I've seen fairly often:

if not {%1} == {}

And so on...

The problem, as you can likely guess, is that the %1 is literally replaced with emptiness. It is not 'an empty string' it is actually a blank spot in your source file at that point.

Then after the replacement, the interpreter tries to parse the if statement and gets confused.

Solution 3 - Windows

You have to do the following:

if "%1" == "" (
    echo The variable is empty
) ELSE (
    echo The variable contains %1
)

Solution 4 - Windows

Another related tip is to use "%~1" instead of "%1". Type "CALL /?" at the command line in Windows to get more details.

Solution 5 - Windows

An alternative would be to set a variable, and check whether it is defined:

SET ARG=%1
IF DEFINED ARG (echo "It is defined: %1") ELSE (echo "%%1 is not defined")

Unfortunately, using %1 directly with DEFINED doesn't work.

Solution 6 - Windows

you have to do like this...

if not "A%1" == "A"

if the input argument %1 is null, your code will have problem.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMxLDevsView Question on Stackoverflow
Solution 1 - WindowsschnaaderView Answer on Stackoverflow
Solution 2 - WindowsjwdView Answer on Stackoverflow
Solution 3 - WindowsDavid anguloView Answer on Stackoverflow
Solution 4 - WindowsDarinView Answer on Stackoverflow
Solution 5 - WindowsmivkView Answer on Stackoverflow
Solution 6 - WindowsskchoeView Answer on Stackoverflow