Monday, May 14, 2012

Windows batch: echo without new line

Two ways to use set with /p to 'echo' without a new line:

echo|set /p=.


<nul set /p=.

Both examples rely on the set command's behaviour when given the '/p' switch. The '/p' switch turns 'set' into a prompt for input. Usually, this would be employed to solicit interactive input from the user. The value entered at the prompt can be stored in a variable, e.g. 'set /p armageddon=Push Big Red Button?', where the variable 'armageddon' is set to the user's response to the prompt question.

The first example works by having 'set /p=.' output the '.', then get a response from the output of  an empty 'echo' statement piped into the command. The response from echo is discarded, because there is no variable defined for the '=' in the 'set' statement. The second example works by redirecting the 'nul' device into the 'set' statement.

Each time the statement is executed, another dot is output on the same line. This technique could be used to make a progress bar in a batch file, e.g. each time through a 'for /f' loop.

The statement could also be wrapped in an if-else block to flag errors, e.g.

if %foo% equ 1 (
    <nul set /p=.
) else (
    <nul set /p=F
)

The output is a series of dots for success, with F's marking failures:
....F...F.

Big thanks to arnep for this elegant solution.

'via Blog this'

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.