0

I have a dynamic variable in my batch script and I need to use it or print it later on in the script, for example

set txt1=hello world
echo %txt1%
set /a num=1
echo %txt%%num%

In the second line in this sample, the result will be "hello world", but in the last line it will be 1, how can I make the last line to print "hello world" using a dynamic variable

kyafi_1800
  • 21
  • 1
  • 3
  • I'd wager that you'd get more than a few hits using this search term, **[batch-file]dynamic variable**; [take a look](https://stackoverflow.com/search?q=%5Bbatch-file%5Ddynamic+variable). – Compo Jul 01 '18 at 08:36
  • Mmmm... This is not a _dynamic variable_, but an _array element_, that is, there are several `txt` elements that are selected via a numeric _index_ or _subscript_. For details on array management in Batch files see [this answer](https://stackoverflow.com/questions/10166386/arrays-linked-lists-and-other-data-structures-in-cmd-exe-batch-script/10167990#10167990). PS: in Batch files the _dynamic variables_ are `time`, `random`, etc. Enter `set /?` and read the part about _"environment dynamic variables"_... – Aacini Jul 01 '18 at 14:26

1 Answers1

1

Don't use an arithmetic expression to assign a number string to an environment variable. That is in most cases useless although always working. So use set "num=1" instead of set /a num=1. For the reason read answer on Why is no string output with 'echo %var%' after using 'set var = text' on command line?

It is necessary to get the last command line parsed twice by cmd.exe which can be reached by either using delayed expansion or using command CALL as explained in detail by answer on How does the Windows Command Interpreter (CMD.EXE) parse scripts?

The solution using command CALL:

set "txt1=hello world"
echo %txt1%
set "num=1"
call echo %%txt%num%%%

The last line is first processed to call echo %txt1% and next processed a second time because of command CALL to echo hello world which is finally executed by cmd.exe.

The second solution using delayed expansion:

setlocal EnableDelayedExpansion
set "txt1=hello world"
echo %txt1%
set "num=1"
echo !txt%num%!
endlocal

The last but one line is first processed to echo !txt1! which is processed a second time because of delayed environment variable expansion to echo hello world on execution of the batch file.

For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.

  • call /?
  • echo /?
  • endlocal /?
  • set /?
  • setlocal /?

Read this answer for details about the commands SETLOCAL and ENDLOCAL.

Mofi
  • 46,139
  • 17
  • 80
  • 143