Skip to content

Instantly share code, notes, and snippets.

@MarkTiedemann
Created August 31, 2017 23:53
Show Gist options
  • Save MarkTiedemann/360f9787557a3031782b470f4791f507 to your computer and use it in GitHub Desktop.
Save MarkTiedemann/360f9787557a3031782b470f4791f507 to your computer and use it in GitHub Desktop.
Set command output to env var in batch script
@echo off
:: print help
if "%~1" == "--help" (
type %~dp0setvar.txt
) else (
:: assign output of command to env var
for /f "delims=" %%i in ('%~2') do set %~1=%%i
if "%~3" == "--echo" (
:: split env var `key=value` and echo value
for /f "delims== tokens=2" %%g in ('set %~1') do echo %%g
)
)
setvar v0.1.0
Unfortunately, `cmd` doesn't have an easy-to-use,
built-in way of assigning the output of a command
to an environment variable.
`setvar` fixes that:
Usage:
$ setvar <var_name> <command> [--echo]
Examples:
$ setvar me whoami
$ echo %me%
c-3po\mark
$ setvar me whoami --echo
c-3po\mark
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment