Syed Galib
Syed Galib

Reputation: 88

How to mention If else condition in batch file

Is there any code system like below :

@echo off  
set /p location=Type Folder Location  
copy "%location%\file.txt" "c:\Folder"  
if copy is done goto ok  
if not goto failed  
:ok  
echo File is copyed succesfully  
:failed  
echo File is not copyed  
echo.  
pause  
exit  

Upvotes: 1

Views: 158

Answers (2)

SachaDee
SachaDee

Reputation: 9545

Like @Magoo saids in your case you just need 1 condition to go forward. But to answer your question: How to mention If else condition in batch file

@echo off
set /a $var=1
if %$var%==1 (goto:ok) else (goto:nok)
:ok
echo OK
exit/b
:nok
echo NOK

You can change the value of $var to check it

Upvotes: 0

Magoo
Magoo

Reputation: 80073

@echo off  
set /p location=Type Folder Location  
copy "%location%\file.txt" "c:\Folder"  
if errorlevel 1 goto failed  
:ok  
echo File is copied succesfully
goto done
:failed  
echo File is not copied  
:done
echo.  
pause  
exit

Normally, when a command succeeds, the "magic" variable errorlevel is set to zero; if it fails, to non-zero.

The syntax if errorlevel n will be true if errorlevel is n or greater than n (this last point is important - if errorlevel 0 will always be true (in normal circumstances).

Unlike many languages, batch has no concept of the end of a "procedure" - it simply continues execution line-by-line until it reaches the end-of-file. Consequently, you need to goto :eof after completing the mainline, otherwise execution will continue through the subroutine code. :EOF is a predefined label understood by CMD to mean end of file. The colon is required.

(in this case, the goto done skips over the 'failed' message - often you want to terminate the batch under certain circumstances. there you'd use goto :eof)

Upvotes: 2

Related Questions