Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behavior of echo command with pipe operator on windows?

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

like image 656
Waqas Ali Avatar asked Mar 02 '23 18:03

Waqas Ali


1 Answers

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%
like image 150
dxiv Avatar answered Mar 15 '23 16:03

dxiv