2

I want to assign the output of running a batch script with arguments to a variable. Please suggest me on how to do this.

Example: The output of datemath.bat %Date_Pattern% - 2 should be assigned to a variable.

Say my date_pattern was 2013 05 03 then my variable will come up with 2013 05 01

1

1 Answer 1

3

There are generally two ways to store the output of a command into a variable. I'm going to assume there is only one line of output to be captured. I'm also assuming the output is on stdout, and not stderr. The command could be a call to a batch file, a call to a subroutine within a batch file, an internal command, a standard external command (executable), or a 3rd party executable - the process for capturing the output into a variable is the same.

1) Redirect the output to a temporary file, and then read the value into a variable using SET /P

call dateMath.bat %Date_Pattern% - 2 >output.tmp
<output.tmp set /p "result="
del output.tmp

Typically the temporary file is created in the %TEMP% folder, but I kept everything in the current directory just for simplicity.

People generally like to avoid temporary files if possible, although sometimes that is the best option.

2) Use FOR /F to capture the output directly, without using a temporary file. FOR /F is a complicated command with many options. It is designed to parse input into delimited tokens. The default delimiter is a space; but you want the entire string to be captured in one variable. So you need to set the delimiter to nothing. FOR /F can read file contents, a string, or command output. You want command output, so the IN() clause should be enclosed in single quotes. The @ symbol is used to suppress echoing of the SET command line.

for /f "delims=" %A in ('dateMath.bat %Date_Pattern% - 2') do @set "result=%A"

If you want to use the above command in a batch script, then the FOR variable percents need to be doubled. Your script probably has echo off, so @ is not needed.

for /f "delims=" %%A in ('dateMath.bat %Date_Pattern% - 2') do set "result=%%A"

There is an entirely different approach you could take: modify your batch script to optionally store the result directly in the variable. You should read the following excellent tutorial from DosTips.com DOS Batch - Function Tutorial The site constantly refers to DOS, but in reality it is a site that specializes in all things dealing with Windows batch scripting.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.