Batch Programming: Capturing Prompts


Prompts always show up at the beginning of a line, so the ability to capture the entire line, prompt and all, gives us another way to prefix desired words onto an existing line

In this example, we will change a prompt to the phrase set value= in order to get it on the same line with -- and preceeding -- the phrase Your command output goes here! The trick used here is redirection. Although we can't redirect the output of a batch file, we can redirect the output of .COM file. When command.com is run as a separate session, the entire output of that session, prompts and all, can be redirected.

@echo off
echo @prompt set value$Q> 1.bat
echo Your Command Output Goes Here!>> 1.bat
echo @prompt $H>> 1.bat
command /c 1.bat > 2.bat

Notice the two additional files generated. 1.BAT is generated on-the-fly, and 2.BAT is the desired output. After generating 1.BAT , COMMAND runs it. 1.BAT will change the prompt to the desired phrase, then run the "Your Command..." line. At this point our command prompt is
set value=
and the command is
Your Command Output Goes Here!
so the on-screen display (if you could see it for the millisecond it exists) is
set value=Your Command Output Goes Here!
We next change the prompt to something invisible ( I chose $H, a backspace) to keep the output clean. That's it. The entire session is redirected into 2.BAT. If you wanted, you could CALL 2.BAT at this point.

Problems:
(1)  Obviously, the first word of the "Your Command..." line MUST NOT be a valid command. Since there is no command called "YOUR", we're okay on this example. If you want to be sure, poison your lines by numbering them.
(2)  Since there is no command called YOUR, we get a "Bad command or file name" message displayed directly to the screen. It doesn't get redirected. To stop this from appearing, put ctty nul just before the command /c line, and put ctty con just after the command /c line.
(3)  The output file has a couple extra blank lines due to all those invisible commands we run. Pipe the output of the command /c line through FIND, looking for "set value=" before redirecting it into 2.BAT.

If you read more about the PROMPT command, you'll find several built-in prompts you can capture which would be otherwise awkward to come by.

Lost? Look at the site map.

Bad links? Questions? Send me mail.

Google
Yahoo
Ask Jeeves