8

I need to do the equivalent of

set ENVAR=`some-command`

In a windows/cmd.exe script. Cygwin is not an option.

For bonus marks: Is there some cmd.exe equivalent of backticks in general?

Joey
  • 344,408
  • 85
  • 689
  • 683
Peter Graham
  • 11,323
  • 7
  • 40
  • 42
  • I have a third-party program that calls cmd.exe with a script and checks the CAUSE environment variable after the script finishes. I can't use another shell directly. – Peter Graham Jul 08 '10 at 00:38
  • Just FYI, how to do this in Linux and Unix: https://unix.stackexchange.com/questions/493081/how-to-create-an-environment-variable-that-is-the-output-of-a-command – RockPaperLz- Mask it or Casket Sep 07 '21 at 00:40

2 Answers2

8

A quick and dirty way would be redirecting it to a file and then reading this, e.g.

some-command>out.txt
set /p ENVAR=<out.txt

I think for can also help you, but I don't remember the exact syntax. Try something like

for /f "usebackq" %x in (`some-command`) do set ENVAR=%x

I probably forgot some token or delim in the options...

mhd
  • 1,339
  • 1
  • 13
  • 14
3

Not "probably", it is absolutely a must to specify "delims=" (it means "no delimiters"), unless you want your variable to only contain up to first space or tab of the input data.

It is recommended to specify "delims=" as the last option to avoid potential confusion in options perception by the operator and by the shell.

I.e.

FOR /F "usebackq delims=" %%a IN (`cygpath.exe -u "%~1"`) DO (
    SET CMDNAME=%%~a
    SHIFT
)

See SS64 article on FOR /F.

AnrDaemon
  • 302
  • 2
  • 9
  • The `delims=` option must be the last one in case you want to specify a space as delimiter. The string `"delims= usebackq"` would define no delimiter, but `"usebackq delims= "` defines the space… – aschipfl Sep 07 '21 at 06:37
  • Right you are. I guess my source was more from a "best practice" camp. I will edit my answer appropriately. – AnrDaemon Sep 07 '21 at 15:01