I wanted to make a batch file to print the value of a variable by passing the name of variable through the command line argument ex.
print.bat username
the content of print.bat are
@echo off
setlocal
set v=%%%1%%%
echo | echo %v%
Although the script is working perfectly but I still don't understand the working of
echo | echo %v%
My understanding of the pipes is that the output of first command (i.e. command at the left side of pipe operator) is passed to the second command (i.e. the command to the right of pipe operator) so according to this the correct way should have been echo %v% | echo
(which does not work).
Can anybody explain this behavior?
Thanks
set v=%%%1%%%
%1
is the first argument passed on the command line, in your example username
. The %%
are then halved when parsing the line, and the lone %
at the end is discarded, leaving v
set to %username%
.
echo | echo %v%
echo %v%
is parsed as echo %username%
, but the pipe forces it to execute in a second instance of the interpreter, where it undergoes another round of parsing which expands %username%
to the value of the username
environment variable.
the correct way should have been
echo %v% | echo
(which does not work)
That does not and cannot work since echo
does not use the standard input stream. The output of the first echo %v%
command is discarded, and the second echo
finds no command line arguments, so it prints the usual ECHO is on
.
Key point here is that the first echo
in echo | echo %v%
is not actually used as an echo
. Its only role is to allow the pipe, which in turn causes the re-parsing of the second echo
command. For example type nul | echo %v%
would work just the same.
However, this could be accomplished more cheaply without unnecessary piping, using call
.
@echo off
setlocal
set "v=%%%1%%"
call echo %v%
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With