Page 1 of 1

string as statement

Posted: 06 Apr 2019 01:04
by sincos2007

Code: Select all

:test2
setlocal EnableDelayedExpansion

set str1=set s1=hi cat & echo %s1%

%str1%

goto :eof


::why this code does not print 'hi cat'
::Thanks 

Re: string as statement

Posted: 06 Apr 2019 05:40
by jeb
This lines executes like

Code: Select all

set str1=set s1=hi cat & echo %s1%

Code: Select all

set str1=set s1=hi cat
echo %s1%  ---  s1 doesn't contain anythig here, therefore "ECHO IS OFF" will be printed
It's always a good idea to use some debugging technics (not only within batch files).
View the variables, with `SET` or delayed expansion, because both show the real content without modifying it.

Code: Select all

setlocal EnableDelayedExpansion

set str1=set s1=hi cat & echo %s1%
SET str1

%str1%
And you should enable ECHO ON to see how each line is executed.

Re: string as statement

Posted: 06 Apr 2019 12:24
by sincos2007
Hi jeb,

I have debugged by your technics:

Code: Select all

:test3
echo on
setlocal enabledelayedexpansion

set str1=set var1=hi cat^&echo !var1!

%str1%

::debug
set str1
output is:

Code: Select all

str1=set var1=hi cat&echo
This shows that when executing value of str1, var1 getting value code is executed but when showing value of var1 at second command in same line, var1 has not get the value.

Does it mean that I cannot write

Code: Select all

set var1
and

Code: Select all

echo !var1!
in same line in string value that would be executed later?

Re: string as statement

Posted: 06 Apr 2019 13:54
by aGerman
It means that exclamation points have a special meaning if delayed expansion is enabled. Variable var gets already evaluated in your outer SET statement but is not yet defined. Thus, you have to escape them, too. Either

Code: Select all

set str1=set var1=hi cat^&echo ^^!var1^^!
or quoted

Code: Select all

set "str1=set var1=hi cat&echo ^!var1^!"
Steffen

Re: string as statement

Posted: 07 Apr 2019 06:28
by sincos2007
Hi Steffen,

Your method works. Thanks.