i am working on a batch script.
i want to store the count of row’s in variable.
like
set var = mysql -uroot -proot -e”select count(*) from table”;
i also tried to do it other way like
set var= mysql -uroot -proot -e "select count(*) from table into outfile 'F:\count.txt'";
for /f %%a in ("F:\count.txt") do (
set output = %%a
echo %output%
pause
)
In above code the variable “output” shows nothing(empty).
please help me out.
I can see at least two issues in your script:
A string in double quotes inside
IN( )is treated as a literal, not as a file path/name, unless you specify theusebackqoption, which enforces different semantics, whereby either double-quoted string or non-quoted one is treated as a file name.You are storing
<space>%%ainto theoutput<space>variable, not%%aintooutput.After you’ve fixed those two, there will remain one (probably, just one) more issue. You are assigning a value to a variable and then evaluating the variable in the same bracketed block (which is your loop body) using immediate variable expansion (
%var%). This cannot work as expected. The thing is, a bracketed block is parsed entirely as a single unit, i.e. all its commands are parsed before the first one executes. As you can guess, your%output%expression will in this case evaluate to nothing, becauseoutputis not yet assigned a value at the time of parsing. (And when it is assigned a value, it will change nothing, because the previous (empty) value will already have replaced the expression.)You can solve this using delayed variable expansion, which, as can be guessed, uses a different timing for evaluation. First, you should enable delayed expansion by issuing the
SETLOCAL EnableDelayedExpansioncommand, then use a slightly different syntax:!var!instead of%var%.So, if we address all the issues mentioned above, the loop may look like this: