Search code examples
batch-fileif-statementsyntaxgoto

( goto was unexpected this time error


My code below is throwing errors. Please help. I am new to batch file scripts. It is showing syntax error and "goto was unexpected this time" error. My motive is to create a batch file which will accept a parameter from user. Based on that parameter, it will perform the tasks. Like if input is sql, it will execute an sql script. If input is foldercreation, it will create a new folder.

@echo off
cls

set /p FileType=Type of file :
if "%FileType%==SQL" (goto sql)
if "%FileType%==TXT" (goto text)
if "%FileType%==BAT" (goto bat)
if "%FileType%==FolderCreation" (goto FolderCreation)
if "%FileType%==FTP" (goto ftp)


:sql
set /p SName=Server Name :
set /p DbName=Database Name :
if exist _Deploy.txt del _Deploy.txt
@echo on
sqlcmd -S %SName% -E -d %DbName% -I -i "D:\Script\Execute_Script.sql" >>_Deploy.txt 2>&1
@notepad _Deploy.txt
exit /b

:text
if exist _Deploy.txt
@echo on
move /-y "D:\artifacts\Art1\test1.txt" "D:\artifacts\Art2\">>_Deploy.txt 2>&1
@notepad _Deploy.txt
exit /b

:bat
if exist _Deploy.txt
@echo on
call testbatchcreatefolder.bat>>_Deploy.txt 2>&1
@notepad _Deploy.txt
move /-y "D:\artifacts\Art1\testbatchcreatefolder.bat" "D:\artifacts\Art2\"
exit /b

:FolderCreation
set /p Mypath=Path please :
set /p Myfoldername=folder name :
set folder_path=%Mypath%\%Myfoldername%
md "%folder_path%"
exit /b

:FTP
if exist _Deploy.txt
@echo on
move /-y "D:\artifacts\Art1\test2.txt" "D:\artifacts\Art2\">>_Deploy.txt 2>&1
@notepad _Deploy.txt
exit /b

pause

set /p delExit=Press the ENTER key to exit...:
:end

Solution

  • if "%FileType%==SQL" (goto sql)
       ^...............^ = one string
    

    So the previous code is equivalent to

    if "this is not valid" (goto sql)
    

    In an if command you need a condition. If it needs to compare two strings it should be

    if "%FileType%"=="SQL" (goto sql)
       ^..........^  ^...^
    

    When the parser replaces the variable reference with its value you end with one quoted string in each side of the == operator

    This change should be made in all the similar lines.

    Also, the lines

    if exist _Deploy.txt
    

    are missing the command part. If the intention is to execute the block of code following the if, then it should be

    if exist _Deploy.txt (
        here the code to execute if the file exist
    )