string as statement

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
sincos2007
Posts: 44
Joined: 05 Apr 2019 05:52

string as statement

#1 Post by sincos2007 » 06 Apr 2019 01:04

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 

jeb
Expert
Posts: 1041
Joined: 30 Aug 2007 08:05
Location: Germany, Bochum

Re: string as statement

#2 Post by jeb » 06 Apr 2019 05:40

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.

sincos2007
Posts: 44
Joined: 05 Apr 2019 05:52

Re: string as statement

#3 Post by sincos2007 » 06 Apr 2019 12:24

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?

aGerman
Expert
Posts: 4654
Joined: 22 Jan 2010 18:01
Location: Germany

Re: string as statement

#4 Post by aGerman » 06 Apr 2019 13:54

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

sincos2007
Posts: 44
Joined: 05 Apr 2019 05:52

Re: string as statement

#5 Post by sincos2007 » 07 Apr 2019 06:28

Hi Steffen,

Your method works. Thanks.

Post Reply