I am attempting to make a script that is called from another script to update him...
This script is downloaded from a server via wget and it is started by other script. It checks version of RunToolkit and, if it isn't v1.1, it downloads the new version...
But when this script is called, it give an error, "unexpected goto".
Hers is the script:
@echo off
echo Latest version is 1.1
:restart
IF EXIST RunToolkit.exe (
FIND /I "1.1" "RunToolkit.exe" > NUL:
IF ERRORLEVEL 0 (
ECHO Your toolkit version is 1.1
echo No updates available!
PAUSE
goto quit
) ELSE (
ECHO Your toolkit is outdated, do you want to update it?
ECHO.
ECHO 1. Yes
ECHO 2. No
ECHO.
SET /P menunr=Select number you want :
IF %menunr%==1 (goto yesupdate)
IF %menunr%==2 (goto quit)
goto what
)
)
:yesupdate
echo Downloading new version!
wget (link deleted for privacy :P)
:what
echo.
echo You entered a wrong number! Retry!
PAUSE
goto restart
:quit
call RunToolkit.exe
Can anyone find the error, please?
First issue, nothing to do with your error is
IF ERRORLEVEL 0 (
Which should alwaays be true. if errorlevel n
means if errorlevel is n OR GREATER THAN n
. There ARE ways of setting errorlevel negative - but normal operation would always set a positive errorlevel, hence if errorlevel 0
should always be true.
Your next problem is that CMD always substitutes the current
value for any %var%
in any logical line, then validates the line. The logical line here starts at IF EXIST
and runs through to the single closing-parenthesis in the first column - 18 physical lines later.
At that time, IF %menunr%==1 (goto yesupdate)
will be evaluated as IF ==1 (goto yesupdate)
because menunr
is undefined WHEN THE LINE WAS PARSED
. This is the source of your UNEXPECTED GOTO
Since you are entering memunr
you need to learn about delayedexpansion
- here's a demo:
@echo off
SETLOCAL
cls
set var=ORIGINAL
echo Start value of var=%var%
for %%i in (1) do (SET var=AFTER
ECHO var is %var% in the for loop
)
echo Final value of var=%var%
ENDLOCAL
ECHO.
echo ---- try again with ENABLEDELAYEDEXPANSION
ECHO.
setlocal enabledelayedexpansion
set var=ORIGINAL
echo Start value of var=%var%
for %%i in (1) do (SET var=AFTER
ECHO var is %var% not !var! in the for loop
ECHO Note: in the loop VAR has old value %var% and new value !var!
)
echo Final value of var=%var%
endlocal
Note the difference between %var%
(the PARSE-TIME
value) and !var!
(the RUN-TIME
value)
ALSO:
If you press simply ENTER
as a response to SET /P menunr=Select number you want :
then menunr
will remain UNCHANGED. Since it had no value, it will still have no value, and hence if you turn on delayedexpansion
by mans of a setlocal enabledelayedexpansion
statement, the logical change
IF %menunr%==1 (goto yesupdate)
to
IF !menunr!==1 (goto yesupdate)
will also suffer the same error.
You need to use
IF "!menunr!"=="1" (goto yesupdate)
to cater for the empty-variable scenario.
(also: the parentheses around the GOTO
here are superfluous, but harmless)