Question

I have written a beep file and it cannot work properly:

@echo off
if "%1"=="" (
(echo.)
) ELSE (
if "%1"=="/?" (
echo BEEP [/? | LOOP [TIMES]]
echo THIS COMMAND IS USED TO BEEP.
) ELSE (
set number2=%2
if "%1"=="loop" (
for /l %%i in (1,1,%number2%) do (echo.)
set number2=
) ELSE (
echo INPUT "BEEP /?" TO SEE HELP.
)
)
)

So here are some examples which SHOULD work but ISN'T working:

beep.bat loop 2

Should beep twice.

beep.bat /?

Is working properly.

THE PROBLEM IS AT beep.bat loop [no] part.
It cannot work, and, no output.

ANY HELP will be appreciated.

Was it helpful?

Solution

@echo off
    setlocal enabledelayedexpansion

    if "%~1"=="" (
        echo(
    ) else if "%~1"=="/?" (
        echo BEEP [/? | LOOP [TIMES]]
        echo THIS COMMAND IS USED TO BEEP.
    ) else if /i "%~1"=="loop" (
        set /a "number2=%~2"
        for /l %%i in (1,1,!number2!) do echo(
    ) else (
        echo INPUT "BEEP /?" TO SEE HELP.
    )

Your problem was delayed expansion. All variable reads inside a block of code (code inside parenthesis) gets replaced with the value in the variable before the block starts to execute. If a variable is changed inside the block, that new value can not be retrieved, as all reads to variables were replaced with values. To solve, enable delayed expansion and, in variables where delayed read is needed, change %var% sintax with !var! to indicate the parser to delay the read until the time of execution.

OTHER TIPS

The echo is too fast.

Add a timeout and use the input parameter %2 directly:

for /l %%i in (1,1,%2) do (
    echo.
    timeout /t 1 /nobreak > NUL
)

This is how I would do it. If they type /? or -h then it will still print the help, and will only loop when two parameters are given.

If no parameter is given then it will echo once.

You can also add a routine to ensure that the %2 is a real number.

echo off
if "%~1"=="" (echo.&goto :EOF)
if "%~2"=="" (
   echo BEEP LOOP [TIMES]
   echo THIS COMMAND IS USED TO BEEP THE SPEAKER (if it has one)
   echo.
   pause
   goto :EOF
)

for /l %%i in (1,1,%2) do (echo.)

A simple beep loop script

@echo off

REM loopNum defaults to 1, caps at 10.

SET loopNum=1
If not "%~1"=="" (
    SET loopNum=%1
)

FOR /L %%i IN (1,1,10) DO (
  @echo 
  IF %%i GEQ %loopNum% GOTO :scriptEOF
)

:scriptEOF

You should be able to interpret this easily.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top