Skip to content

Instantly share code, notes, and snippets.

@josepsmartinez
Last active September 8, 2022 09:48
Show Gist options
  • Save josepsmartinez/496ba062f1c2182f5993fcf395a11e57 to your computer and use it in GitHub Desktop.
Save josepsmartinez/496ba062f1c2182f5993fcf395a11e57 to your computer and use it in GitHub Desktop.
Windows .bat: attributing command output to variable (solution from https://stackoverflow.com/a/48404829/4449273)
FOR /F "tokens=* USEBACKQ" %%g IN (`<command>`) do (SET <variable name>=%%g)
@josepsmartinez
Copy link
Author

josepsmartinez commented Sep 8, 2022

%%g or %g?

As noted in the solution's thread, the %% sequence only works when the code line runs in a batch file. Otherwise, a single % should be used.

Example

Consider the scenario in which I want to attribute the current date (which is returned by cmd's date /t command) to a variable called current_date.

The line to be inserted in a .bat script is the following:

FOR /F "tokens=* USEBACKQ" %%g IN (`date /t`) do (SET current_date=%%g)

In a regular cmd terminal, you can debug the variable attribution (but don't forget to replace the %% with %!). A code block suggested for debugging the above example is the following:

SET current_date=not the date i want
echo %current_date%
FOR /F "tokens=* USEBACKQ" %g IN (`date /t`) do (SET current_date=%g)
echo %current_date%

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment