Consider the cmd/batch script program.bat
which accepts optional piping and command-line arguments. The script will be executed in four different ways:
program.bat
: without piping and arguments
program.bat <arguments>
: with arguments
<command> | program.bat
: with piped multiline string
<command> | program.bat <arguments>
: with both piped multiline string and arguments
It is important to note that the output of <command>
is not necessarily a single line (e.g., dir
). The script should work with or without any of the piped information and arguments. Case 2 can easily be achieved using the %*
to reach the arguments in the form of a list/array (reference). If I were sure that there will always be a one-line string piped I could use: (reference)
SET /p "piped="
However, this will expect the user to enter something in cases 1 and 2, when nothing is piped, which is undesirable. Plus, this only stores the first line of the <command>
output to the piped
variable. I would appreciate if you could help me know how I can have a script that:
- works in all 4 above scenarios
- stores the optional piped multiline string into a variable
P.S. To test the answer by @aschipfl, I created a file program.bat
with the content:
@echo %CmdCmdLine%
I ran it in 3 different ways:
cmd
<someRandomCommand> | program.bat
resulting
C:\WINDOWS\system32\cmd.exe /S /D /c" program.bat"
C:\WINDOWS\system32\cmd.exe /S /D /c" program.bat"
although it is a brilliant workaround to detect the piping itself, it can not distinguish if the program.bat
is the one who is piping or the one which is being piped to. This is not an issue that I had thought about.
Copyright Notice:Content Author:「Foad S. Farimani」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/64489414/a-batch-script-that-stores-optional-piped-multiline-string-and-optional-argument