user723205
user723205

Reputation: 13

Write variables to file as %VAR% not as the value of the variable in BAT

Write variables to file as %VAR% not as the value of the variable, as well ask making tasklist function properly when redirecting output.

Code im using to write to file:

echo tasklist /FI "IMAGENAME eq %ZOEXT%" 2>NUL | find /I /N "%ZOEXT%">NUL >> boot.bat
echo if "%ERRORLEVEL%"=="1" start /d "%ZODIR%" %ZOEXT% >> boot.bat

Result:

tasklist /FI "IMAGENAME eq Zoiper.exe"  
if "0"=="1" start /d "C:\Documents and Settings\mgladman\Desktop\Zoip\Zoiper Communicator\" Zoiper.exe 

What I want added to boot.bat:

tasklist /FI "IMAGENAME eq %ZOEXT%" 2>NUL | find /I /N "%ZOEXT%">NUL
if "%ERRORLEVEL%"=="1" start /d "%ZODIR%" %ZOEXT%

If you want i can publish whole code not just segment, it is a cool script :P Just has this small issue.

Only "workaround" i can think is to make the first script, to echo echo in the first file and write the correct system data (this has to be a portable script, so that would work, but would be messy as)

Upvotes: 1

Views: 16130

Answers (3)

mousio
mousio

Reputation: 10337

Just double the percentage signs to escape them, and use carets to escape most other special characters. Here is how I would do it:

(echo tasklist /FI "IMAGENAME eq %%ZOEXT%%" 2^>NUL ^| find /I /N "%%ZOEXT%%"^>NUL)>>boot.bat
(echo if "%%ERRORLEVEL%%"=="1" start /d "%%ZODIR%%" %%ZOEXT%%)>>boot.bat

Upvotes: 0

manojlds
manojlds

Reputation: 301347

You can escape the % using ^ if you are in command line.

For example:

set var=test
echo %var%

echoes test

set var=test
echo ^%var^%

echoes %var%

In batch file you have to use double % -

set var=1
echo %%var%%

echoes %var%

Upvotes: 2

jeb
jeb

Reputation: 82337

The % can be escaped inside of an batch with a percent.

echo %%var%%

This doesn't work on the command line, as the parser works there a bit different.
There didn't exists an escape character for the percent, but percents are preseverd if the variable doesn't exist.

set "var="
set "var2=content"
echo %var%  %%var2%%

results in
%var% %content%

Upvotes: 2

Related Questions