Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Batch Files: if else

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?

like image 441
MxLDevs Avatar asked Apr 16 '11 00:04

MxLDevs


People also ask

Is there else if in batch file?

However, you can't use else if in batch scripting. Instead, simply add a series of if statements: if %x%==5 if %y%==5 (echo "Both x and y equal 5.")

What is == in batch file?

[ == ] (Double Equals) The "IF" command uses this to test if two strings are equal: IF "%1" == "" GOTO HELP. means that if the first parameter on the command line after the batch file name is equal to nothing, that is, if a first parameter is not given, the batch file is to go to the HELP label.

What is %% A in Batch Script?

Use double percent signs ( %% ) to carry out the for command within a batch file. Variables are case sensitive, and they must be represented with an alphabetical value such as %a, %b, or %c. ( <set> ) Required. Specifies one or more files, directories, or text strings, or a range of values on which to run the command.

Is it possible to apply if function in CMD?

If the condition specified in an if clause is true, the command that follows the condition is carried out. If the condition is false, the command in the if clause is ignored and the command executes any command that is specified in the else clause. When a program stops, it returns an exit code.


1 Answers

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.

like image 178
schnaader Avatar answered Oct 22 '22 21:10

schnaader