S
S
Sergey Blokhin2011-09-21 11:52:42
bash
Sergey Blokhin, 2011-09-21 11:52:42

Assigning a value to a variable in DOS?

How to assign the result of an external program execution to a variable in a .bat file?
Similar to bash: variable=`grep --count value filename`.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
F
Fastto, 2011-09-21
@Fastto

The assignment is done with the statement SET
SET set is_finded=1
echo !is_finded!
will give out 1
But it’s exactly the external program ... you can’t think of it right away, but you can do it like this:
1. Write the result to a file
2. read the file through FOR and assign the first line to a variable with SET

K
korvindest, 2011-09-21
@korvindest

In batch files, external programs can only directly write the result to the %ErrorLevel% variable, this is the result of the program int main(...){ return 0;}.
There are not more direct ways, the most direct of them is processing the output (stdout) of the program with a for loop. It's done like this:
for /F "tokens=*" %%f in ('myprogram.exe') DO set myVar=%%f
But this option is only good if everything you need fits on one line.
If the program produces a lot of lines, then in the loop it is necessary to set the processing and take into account the locality of changes with the variable. (In batch files, any actions to change variables performed inside the loop do not go beyond the loop)
To do it like this:
for /F "tokens=*" %%f in ('myprogram.exe') DO (
call set myVar=% myVar%%%f
)
The line break character in batch files cannot be placed in a line in any (not cheating) way.
Then there are even more perverse crutch ways through the file, but let me avoid them.
If this is really vital for you, then I can give advice and even help with writing a batch file. Just writing batch files with a bypass of all crutches is an art that needs to be learned for years (If at all you need to study :-)).

R
Roman Gogolev, 2011-09-21
@romka777

Google for "errorlevel".

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question