Windows command prompt: Using a variable set in the same line of a one-liner

后端 未结 4 1242
别那么骄傲
别那么骄傲 2021-02-13 23:29

Okay, I learned that one can use & or && to combine multiple commands into a single line, but it seems that variables that are set

4条回答
  •  醉梦人生
    2021-02-14 00:05

    Though I accepted @jeb's answer, ultimately I had to go another route, because I needed to pipe the output of my command, and doing so on call led to mangled results. Indeed, the documentation for call itself remarks,

    Do not use pipes and redirection symbols with call.

    Instead, reminded by @Blorgbeard of cmd's /v option (and I believe that should be lowercase, not uppercase), I realized I could simply start a subprocess:

    C:\Users\Andrew>cmd /v /c "set foo=hello, world!&& echo !foo!"
    hello, world!
    

    (For some reason, /v must appear before /c.) Within the quotes, I was able pipe my output to other utilities. One tip for those taking this path: If you find yourself needing to use quotes within those quotes, I suggest avoiding them altogether and trying character codes, e.g. \x20 for space, \x22 for double quotes, and so on.

    For example, this was the eventual solution to my problem (warning: may cause eyes to bleed):

    C:\Users\Andrew>cmd /v /c "set source=C:\source& set target=C:\target& set archive=C:\archive& robocopy.exe !source! !target! /l /e /zb /xx /xl /fp /ns /nc /ndl /np /njh /njs | sed -e s/^^[\t\x20]\+// | sed -e /^^$/d | sed -e s/^!source:\=\\!// | sed -e s/.*/xcopy\x20\/Fvikrhyz\x20\x22!source:\=\\!^&\x22\x20\x22!archive:\=\\!^&\x22/"
    

提交回复
热议问题