Batch files. IF statements?

I have a batch file that should apply the attrib + h command to the file, then output to a txt file and display the contents on the screen. This should also be done if the file was not provided or not found. I still have this, but I can't get it to work:


:TOP IF EXIST "%1" GOTO COMMAND ) ELSE ( GOTO ERROR1 :COMMAND attrib +h %1 SHIFT GOTO TOP GOTO END :ERROR1 IF "%1"=="" GOTO ERROR2 ) ELSE ( GOTO ERROR3 :ERROR2 ECHO. ECHO No file(s) provided. Please re run the batch file. GOTO END :ERROR3 ECHO. ECHO The file was not found. Please re run the batch file. GOTO END :END 

This is my first computer course, and any help would be greatly appreciated. Thanks.

+8
windows cmd if-statement batch-file
source share
3 answers

There are several issues with this code. First, batch files require specific syntax with IF / ELSE IF .

Something like that

 IF EXIST "%1" ( echo "it here!" ) ELSE ( echo "it isn't here!" ) 

works correctly and something like this

 IF EXIST "%1" ( echo "it here!" ) ELSE ( echo "it isn't here!" ) 

not. A bracket restricts a block, so your IF command will execute everything between ( and ) if it evaluates to true.

Secondly, you really don't need any ELSE statements. Because you use GOTO commands immediately before your ELSE commands, you will never reach the second GOTO command if the first IF is true.

Finally, with the code you are currently showing, the tag :TOP that you have is not needed.

After all this, you should leave something similar to this:

 @ECHO off IF EXIST "%1" ( GOTO COMMAND ) GOTO ERROR1 :COMMAND echo "You entered a file correctly, and it exists!" GOTO END :ERROR1 IF "%1"=="" ( GOTO ERROR2 ) GOTO ERROR3 :ERROR2 ECHO. ECHO No file(s) provided. Please re run the batch file. GOTO END :ERROR3 ECHO. ECHO The file was not found. Please re run the batch file. GOTO END :END 
+12
source share

Just some problems with parenthesis and thread logic

 @ECHO OFF IF "%~1"=="" GOTO ERROR1 :TOP IF NOT EXIST "%~1" GOTO ERROR2 attrib +h "%~1" IF "%~2"=="" GOTO END SHIFT GOTO TOP :ERROR1 ECHO. ECHO No file(s) provided. Please re run the batch file. GOTO END :ERROR2 ECHO. ECHO The file "%~1" was not found. Please re run the batch file. GOTO END :END 
+2
source share

I am not familiar with Batch, but it looks like your If statement is formatted incorrectly.

 IF EXIST "%1" ( GOTO COMMAND ) ELSE ( GOTO ERROR1 ) 
0
source share

All Articles