How to detect if input comes from pipe or redirected file
Posted: 25 Oct 2011 07:40
Hi,
this is an interessting code, as it fits to some other problems (like set /p, and FOR/F file reading)
You can detect how your batch is called
or
or
From Frank P. Westlake alt.msdos.batch.nt
jeb
this is an interessting code, as it fits to some other problems (like set /p, and FOR/F file reading)
You can detect how your batch is called
Code: Select all
type file.txt | myBatch.bat
or
Code: Select all
< file.txt myBatch.bat
or
Code: Select all
myBatch.bat
From Frank P. Westlake alt.msdos.batch.nt
Code: Select all
:: inputDemo2.cmd
:: From the desk of Frank P. Westlake, 2011-09-21
::
:: Determines if there is redirected or piped input waiting and identifies
:: which it is. This test conforms to the precedence of REDIRECTION over PIPE.
::
:: This test is not reliable because if file handle 3 is mishandled by any
:: process in this console group then the handle can become lost or confused.
::
:: This test is not reliable because there are other command line
:: configurations which will pass the test as a PIPE but which have no pipe.
::
:: Unfortunately this test prints a blank line in the console window
:: if input is not REDIRECTION.
@Echo OFF
SetLocal EnableExtensions
:: This file catches the error report if input is REDIRECTION. It will be deleted.
Set "TempFile=%TEMP%\inputTest"
:: INPUT either remains undefined or it is defined with either "REDIRECTION" or "PIPE".
Set "INPUT="
:: BEGIN TEST.
:: Print something redirected to the console window. This redirection fails if the
:: input stream has been redirected from a file; an error report is sent to "%TempFile%".
:: ERRORLEVEL does not receive the value of this error so the report is necessary.
:: This redirection does not fail if it is done in FOR's execution chamber so it must be
:: done here.
Echo(>&3 2>"%TempFile%"
For %%f in ("%TempFile%") Do (
ERASE "%TempFile%"
REM If file size is not 0 there was a redirection error so the input type is REDIRECTION.
If "%%~zf" NEQ "0" (
Set "INPUT=REDIRECTION"
) Else (
REM "I'm_HERE"'s pipe test. Determine if a PIPE is indicated.
Echo %CMDCMDLINE%|FINDSTR "\"/c\" %0">NUL: && Set "INPUT=PIPE"
)
)
:: Finished. Show the result.
If DEFINED INPUT (
Echo Input type is %INPUT%
REM Show the input.
MORE
) Else (
Echo No PIPE and no REDIRECTION.
)
jeb