简体   繁体   中英

I need to echo ten lines to a text document using a batch file with echo off. The file gets saved, but each line says ECHO is off. my batch file is-

@echo off  
color a    
:ini  
set /p  1= %random%    
set /p  2= %random%   
set /p  3=  %random%  
set /p  4=  %random%  
set /p  5=  %random%  
set /p  6=  %random%  
set /p  7=  %random%  
set /p  8=  %random%  
set /p  9=  %random%  
set /p  10=  %random%

setting random numbers

(  

echo %1%  
echo %2%  
echo %3%  
echo %4%  
echo %5%  
echo %6%  
echo %7%  
echo %8%  
echo %9%  
echo %10%  
)>file.txt

trying to echo them to a file My complication is that echo is off. I need it to be off.

Variables should not be named just a number. Per dbenham's comment below:

%1% is interpreted as %1 (the first script argument) which happens to be undefined in this case, followed by a lone % which is simply consumed. Generally, you should not define a variable with a name beginning with a number. But you can access such variables if you use delayed expansion - %1% does not work, but !1! does work.

So in your case the parser encounters an invalid variable (eg %1% ) so it only processes the ECHO command which simply outputs if ECHO is on or off.

Aside from that your script seems a bit off as you are attempting to prompt for 10 values using a random number as the prompt text.

If you just need to output 10 random numbers, you can do it "gracefully" using a FOR loop:

@ECHO OFF
SETLOCAL EnableDelayedExpansion

SET FileName=file.txt
SET NumberOfValues=10

REM Remove existing file if it exists.
IF EXIST "%FileName%" DEL "%FileName%"

FOR /L %%A IN (1,1,%NumberOfValues%) DO ECHO !RANDOM!>>file.txt

ENDLOCAL

Alternately, a more sucinct approach would be this one liner which you can run straight in the Windows command prompt (no batch file needed):

CMD /V:ON /C FOR /L %A IN (1,1,10) DO @ECHO !RANDOM!>file.txt

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM