Reputation: 1
I'm using Windows commandline scripts. What I wanna do is to execute a command "A" which is generated by another command "B" as its output, I also may want to first check if the command exists before executing it. Does anyone here know how to do that? Thanks in advance!
Upvotes: 0
Views: 94
Reputation: 36328
A simple approach which should work in most cases is:
for /F "tokens=*" %%i in ('a.exe') do %%i
or
for /F "tokens=*" %%i in ('a.exe') do if "%%i" NEQ "" %%i
Upvotes: 0
Reputation: 130879
The classic approach is to do redirect your output to a script file as Eugen Rieck suggested. It can be refined by writing to the temp folder and deleting the temp script when finished. I'm incorporating a random number into the temp script name to make it less likely that two simultaneouse instances of your script will not interfere with eachother.
@echo off
setlocal
set script="%temp%\temp%random%.bat"
commandA >%script%
call %script%
del %script%
Your commandA may not produce any output. Executing an empty script will not cause any errors. But if you want, you can detect that the script is empty by the following:
for %%A in (%script%) do if %%~zA equ 0 echo The script is empty.
The script can be built using multiple commands:
commandA >%script%
commandB >>%script%
commandC >>%script%
or more efficiently as:
>%script% (
commandA
commandB
commandC
)
A non-classical approach is to store the commands in a variable instead of a script file, and then execute the expanded value as a macro. The execution of the macro may be significantly faster than execution of a script because it is all memory based. But the rules for successfully building a functioning macro are more complex then building a script. Also the macro is limited to a maximum of 8191 characters (bytes) - the maximum length of a batch environment variable.
It is even possible to create a macro that will accept arguments and return values!
A tremendous amount of work has been done with batch macros at the DOSTips site. Here are two important references if you are interested in trying them out:
http://www.dostips.com/forum/viewtopic.php?p=7330 A good place to start that shows the development of the concept, and many of the key components
http://www.dostips.com/forum/viewtopic.php?p=11344 The latest and greatest with a much improved syntax for macros with arguments
Upvotes: 1