batch script echo dynamic variable [duplicate]

狂风中的少年 提交于 2021-01-29 08:53:55

问题


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


回答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.



来源:https://stackoverflow.com/questions/51120907/batch-script-echo-dynamic-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!