我想从批处理文件中访问 STDIN 后 其他一些命令。我知道 .BAT 文件中的第一个命令接收 STDIN,但我想先运行一些其他命令,然后捕获 STDIN。我还希望它与流式 STDIN 一起使用,即在开始时将 STDIN 捕获到文件是 Not Acceptable (请参阅下面的解决方法)。
现在,我明白 CON
是代表 STDIN 的"file"和 TYPE CON
将输出(回显)STDIN。这在批处理文件中似乎根本不起作用。事实上,它似乎不代表标准输入,而是代表用户/主机通过键盘输入。
测试.bat
TYPE CON > output.txt
试运行:
C:>TYPE myfile.txt | test.bat
预期结果:
myfile.txt
复制到 output.txt
.实际结果:批处理等待用户输入(忽略传递给它的内容)并将键盘上键入的用户输入写入
output.txt
.解决方法
作为解决方法:以下
test.bat
工作但不支持流输入(例如来自 tail
命令):findstr "^" STDIN.txt
:: I can now run some other commands
:: And finally access my STDIN via STDIN.txt
TYPE STDIN.txt | AWK /e/ > output.txt
更新:背景故事:
我有一个简洁的 CMD,它使用 powershell 下载(通过 HTTP)任意 .ps1 脚本(就像包管理器一样)并即时执行它。如果我打电话
REMEXEC.bat mymodule foo bar
它加载并执行 mymodule.ps1
带参数foo
和 bar
.除了管道、流式输入之外,这对于每个场景都非常有效。使用
findstr "^"
适用于管道输入,但不适用于开放流。使用 say AWK /.*/
因为我的 BAT 的第一行让我得到了流式输入,但只是把问题推到了一边。最终我想要一个
something.bat
看起来像这样(伪代码):downloadPSModule( "http://myrepo.com/modules/%1.ps1" )
STDIN | executePSModule %2 %3 %4
捕获 22 是
downloadPSModule
发生在 executePSModule
之前因此无法访问 STDIN(为 BAT 的第一行保留的特权)。
最佳答案
如果您需要从控制台检索输入或从 stdin 流中隔离读取以不消耗管道数据,我会尝试直接从控制台读取类似的内容
@echo off
setlocal enableextensions disabledelayedexpansion
rem Part that reads from console, not piped input
< con (
set "data="
set /p "data=Type something: "
)
echo(
echo You have typed: [%data%]
echo(
rem Part that reads piped input
find /v ""
执行时
W:\>type test.cmd | test.cmd
Type something: this is a test
You have typed: [this is a test]
@echo off
setlocal enableextensions disabledelayedexpansion
rem Part that reads from console, not piped input
< con (
set "data="
set /p "data=Type something: "
)
echo(
echo You have typed: [%data%]
echo(
rem Part that reads piped input
find /v ""
关于batch-file - 捕获通过管道传输到批处理文件的真正 STDIN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55692516/