Skip to content

Instantly share code, notes, and snippets.

@tw-Frey
Created July 11, 2022 14:22
Show Gist options
  • Select an option

  • Save tw-Frey/4c693c06e4a1c94361d457a1d983c9b8 to your computer and use it in GitHub Desktop.

Select an option

Save tw-Frey/4c693c06e4a1c94361d457a1d983c9b8 to your computer and use it in GitHub Desktop.
Set output of a command as a variable (with pipes)

我想要

git show -s --format=%ci abcde12344

結果塞入 set variable

因為 command 裡有 %

導致用 for /f ... in (`command`) do ... 會有問題

後來找到一個 magic 做法

(command & echo.)>2 & (set /p aaa=)<2

例如

(git show -s --format='%ci' abcde12344 & echo.)>2 & (set /p aaa=)<2

如此能將 commit date 塞入 環境變數 aaa


回答者是如此解釋

(cmd & echo.) >2 & (set /p =)<2

The "secret sauce" being the "closely guarded coveted secret" that "echo." sends a CR/LF (ENTER/new line/0x0D0A). Otherwise, what I am doing here is redirecting the output of the first command to the standard error stream. I then redirect the standard error stream into the standard input stream for the "set /p =" command.

簡單說就是

set /p aaa= 是提問式設定環境變數

在提問之前

透過

cmd & echo. 將結果串聯 CR/LF (ENTER/new line/0x0D0A) 存到 2 這個檔案

然後用 <2 這個檔案內容 倒給 set /p aaa=

有一個缺點是

會多一個 2 這個檔案

避免進入版控

可以用 2.log

(我的版控會排除 *.log 檔案)


來源

https://stackoverflow.com/questions/14952295#answer-61666083

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