Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can one pass a variable via a GOTO or can one CALL but end w/o return?

Tags:

batch-file

Let's say you have a batch file like this:

@echo off
setlocal

:part1
echo.
echo Part 1: Your Name
echo.
if "%1"=="err1" echo * You must supply a name! *&echo.
echo Please enter your name below.
echo.
set /p yourName=": "
if "%yourName%"=="" call :part1 err1
if /i "%yourName%"=="/q" goto :eof
goto :part2

:part2
echo.
echo Part 2: Your Age
echo.
if "%1"=="err1" echo * You must supply your age! *&echo.
echo Please enter your age below.
echo.
set /p yourAge=": "
if "%yourAge%"=="" call :part2 err1
if /i "%yourAge%"=="/q" goto :eof
goto :part3

:part3
echo.
echo Part 3: Your Favorite Number
echo.
if "%1"=="err1" echo * You must supply the number! *&echo.
echo Please enter your favorite number below.
echo.
set /p yourNum=": "
if "%yourNum%"=="" call :part3 err1
if /i "%yourNum%"=="/q" goto :eof
goto :part4

:part4
echo.
echo We're done!
echo.
echo Thanks %yourName%, I now know you are %yourAge% and like # %yourNum%!
goto :eof

I want to validate input and also be able to abort the process at each step. It works grand; until someone screws up and triggers the validation. I tried to goto :label err1 but GOTO doesn't allow passing parameters. So I switched to CALL. Problems are 1 it seems to retain %1 as it goes, because after I try to enter a blank name it yells at me to enter name. I do, then on the next screen it immediately yells that I have to enter age though I didn't get a chance yet. Second problem is if I try to terminate, goto :eof just closes the CALL loop and sends me back to where the CALL originated and it continues on.

What is the right way to handle this?? Thanks!

like image 577
Doug Matthews Avatar asked Nov 28 '25 19:11

Doug Matthews


1 Answers

To take your question title literally:

  1. Can one pass a variable via a GOTO?
    No, you can't pass data via a goto :label use a variable.
  2. can one CALL but end w/o return?
    No, a goto :eof or exit /b or implicit reaching the end of file in the called sub returns to the caller, but:

you can pass back an errorlevel and act upon that with

  • conditional execution (|| on fail / && on success) or
  • checking an if errorlevel 1.

@echo off
for /l %%i in (1,1,100) do call :Check %%i || goto :End
Echo Past for
:End
Echo Label End
pause
goto :Eof
:Check
Echo Check %1
if %1==5 Exit /B 1

Sample output:

> SO_50525014.cmd
Check 1
Check 2
Check 3
Check 4
Check 5
Label End

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!