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?
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.")
[ == ] (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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With