In a .bat script, I have a variable that contains &
and needs to be passed to multiple commands, one of which is a pipe.
Concept code which doesn't work:
set foo="1 & 2"
command1 --foo %foo% --bar
echo %foo% | command2 --stdin
After trying various solutions from here and here, I ended up quoting the value of the variable (as opposed to escaping and not quoting, or quoting the entire "var=value").
This works when passing an argument to commands; but when using echo in a pipe, the quotes are also passed to stdin:
setlocal enableExtensions enableDelayedExpansion
set foo="1 & 2"
echo %foo% | sort
Output (as expected):
"1 & 2"
Next, I added delayed expansion in order to remove the quotes, but now the pipe character becomes a literal character in the echo instead of running both commands:
setlocal enableExtensions enableDelayedExpansion
set foo="1 & 2"
echo !foo:"=! | sort
Output:
1 & 2 | sort
How do I convince the script to actually run the pipe instead of making it a literal string?
In case it matters, I'm running this in Windows 10.
Note: using sort
above is simply an example of an arbitrary command, convenient because it takes stdin and prints it back, similar to the cat
command in Linux.