1

I am writing a batch script and I am having trouble echoing a variable, here is the script,

@echo off
set num1=1
set num2=10
set /a "out=%num1%*%num2%"
echo %out%
pause`

The output I receive is 10 which makes sense but I want it to echo 'num1' ten times instead of multiplying 'num1' by 'num2'. So I want the output to be 1111111111.

Also I don't want to loop the command 10 times as I am putting the output into a text file with 'output>> file.txt' otherwise I will end up with this in the text file,

1
1
1
1
1
1
1
1
1
1

I want to end up with 1111111111, thank you.

jeb
  • 78,592
  • 17
  • 171
  • 225
Jacob
  • 48
  • 6

4 Answers4

2
@ECHO OFF
SETLOCAL
set num1=1
set num2=10
SET "out="&FOR /L %%a IN (1,1,%num2%) DO CALL SET "out=%%out%%%%num1%%"
echo %out%
GOTO :EOF

The SET "out=" and FOR /L %%a IN (1,1,%num2%) DO CALL SET "out=%%out%%%%num1%%" may be on separate lines if desired. Setting out to nothing is simply a safety measure to ensure that if it contains a value, it's cleared first.

The for /L performs the call command num2 times.

The call command executes SET "out=%out%%num1%" in a subprocess because each %% is interpreted as an escaped-% (% is the escape character for %) - "escaping" a character means turning off its special meaning.

The syntax SET "var=value" (where value may be empty) is used to ensure that any stray trailing spaces are NOT included in the value assigned.

Magoo
  • 77,302
  • 8
  • 62
  • 84
1

Just to show a different method with set /A and a loop:

@echo off
set /A "num1=1,num2=10,out=0"
:loop
set /a "out*=10,out+=num1,num2-=1"
If %num2% gtr 0 goto :loop
echo %out%
pause
1

This is the simplest way to solve this problem, using Delayed Expansion.

@echo off
setlocal EnableDelayedExpansion

set num1=1
set num2=10
set "out="
for /L %%i in (1,1,%num2%) do set "out=!out!%num1%"
echo %out%
pause

PS - The multiply term is not exact in this case; perhaps "echo a variable the times indicated by another variable" be more clear...

Community
  • 1
  • 1
Aacini
  • 65,180
  • 12
  • 72
  • 108
1

If what you want is to print num1 num2 times in the same line you can do something like:

@echo off
set "num1=1"
set "num2=10"
(for /L %%i in (1,1,%num2%) do set /p "=%num1%" <nul
echo()>file.txt

The command set /p "=%num1%" <nul prints the text %num1% in the current line without the LF character. So num1 gets printed num2 times in the same line.

Compo
  • 36,585
  • 5
  • 27
  • 39
dcg
  • 4,187
  • 1
  • 18
  • 32