Windows Batch脚本将stdout重定向到我们刚刚运行的EXE的stdin [英] Windows Batch script to redirect stdout to stdin of an EXE we've just run
问题描述
我知道在批处理脚本中运行EXE时的正常行为是让批处理脚本在继续执行之前等待EXE退出,但是有什么方法可以使批处理脚本继续执行,但是将其stdout重定向到EXE的标准输入?
I know the normal behaviour when running an EXE in a batch script is for the batch script to wait for the EXE to exit before continuing, but is there any way to get the batch script to continue execution, but redirect its stdout to the stdin of the EXE?
基本上,我正在尝试实现这种巧妙的技巧或类似的方法...
Basically I'm trying to achieve this neat trick or something similar...
@ECHO OFF
echo This is a windows batch script...
dir /p C:\
C:\cygwin\bash.exe <--- Do some magic here
echo This is a bash shell script...
ls -la /cygdrive/c/
exit
echo We're back to the windows batch script again
REM Note: being able to return to the batch script isn't important
关于如何实现这一目标的任何想法?谢谢.
Any ideas on how to achieve this? Thanks.
推荐答案
这应该有效:
@ECHO OFF
echo This is a windows batch script...
dir /p C:\
(
ECHO echo This is a bash shell script...
ECHO ls -la /cygdrive/c/
ECHO exit
) | C:\cygwin\bash.exe
echo We're back to the windows batch script again
编辑:回复评论
如果您不想在每个bash行中添加 ECHO
,则可以使用以下方法:
If you want not to add ECHO
to each bash line, you may use this method:
@ECHO OFF
echo This is a windows batch script...
dir /p C:\
rem Get the number of the first line in this file that start with "###"
for /F "delims=:" %%a in ('findstr /N "^###" "%~F0"') do set "line=%%a" & goto break
:break
rem Pass from that line to end of this file to bash.exe
more +%line% "%~F0" | C:\cygwin\bash.exe
echo We're back to the windows batch script again
goto :EOF
#################################################################
# The remainder of this file is a bash script running in cygwin #
#################################################################
echo This is a bash script!!
ls -la /cygdrive/c/
编辑#2 :
我借用了SonicAtom的方法,并对其进行了少许修改,以使其更简单.在这里:
I borrowed SonicAtom's method and slightly modified it in order to make it simpler. Here it is:
@ECHO OFF
setlocal
rem This is a magic trick to run the bottom half of this script as a bash script
if not defined _restarted (
set _restarted=true
cmd.exe /Q /D < "%~F0"
rem Put any cleanup commands here
echo/
echo Bash script finished
pause
exit /B
)
cls
"C:\cygwin\bin\bash.exe"
#################################################################
# The remainder of this file is a bash script running in cygwin #
#################################################################
echo This is a bash script!!
ls -la /cygdrive/c/
这篇关于Windows Batch脚本将stdout重定向到我们刚刚运行的EXE的stdin的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!