Home > Software design >  Save output of a command as a variable (Windows command prompt)
Save output of a command as a variable (Windows command prompt)

Time:11-30

Say I have the command:

python --version > PythonVersion.txt

A file called PythonVersion.txt is created. In my case the contents are "Python 3.9.13".

Can the output of a command be saved as a variable? I'd like to be able to do something like the following:

@echo off
set "PythonVersion=python --version"
echo Your Python installation is: %PythonVersion%

The expected output might be Your Python installation is: Python 3.9.13, but of course the above script isn't valid and produces Your Python installation is: python --version.

CodePudding user response:

@echo off
for /F "delims=" %%a in ('python --version') do @set lastline=%%a
echo.%lastline%

If the output is multiple lines, you might have to filter the command output with ^| find ... to just get the line you are interested in (unless you want the last line) because for will loop until there are no more non-empty lines...

  • Related