Windows Batch Scripting - Displaying lines

command_prompt.pngProviding feedback for the user about the status of our scripts is really important. We would like to know if everything is fine - or if not, why? Let me show you some tricks which can take the well-known ECHO command a little bit further!
Redirect / hide normal and/or error output
Kind of a must for understandable results. Redirecting can be done with the > character, which can be placed after ECHO or any other external command. When using NUL as a "file name" the text redirected will be discarded completely. What makes this more funny, Windows uses two kind of outputs for displaying text, STDOUT (normal) and STDERR (error). Normally both appears in the console, unless... :) Give it a try. NET USE > nul will show no output at all, but NET InvalidCommand will show you the usage. That's because NET command is using the error output in case of... errors :)
ECHO This will be written to a file > C:\MyFile.txt
ECHO This will be discarded completely > nul
ECHO Both error and normal outputs are ignored > nul 2>&1
ECHO Error output ignored, normal output redirected to file > C:\MyFile.txt 2>nul

Escaping
Batch reserves specific characters for specific actions. Like > is used for redirection. What happens if you want to print that character out? Escape it.
ECHO 100 ^> 99

Displaying a line without line break
I have to admit, this is one of my favorite. With a bit of trick, you can make ECHO not to jump to the next line:
@ECHO OFF
ECHO/|SET /P=Doing some stuff...
REM Let's do something, which will succeed!
NET USE > nul
IF ERRORLEVEL 1 (ECHO  Failed!) ELSE (ECHO  OK!)
ECHO/|SET /P=Doing some more stuff...
REM Now let's fail...
NET InvalidCommand > nul 2>&1
IF ERRORLEVEL 1 (ECHO  Failed!) ELSE (ECHO  OK!)

Alignment
For our scripts to be more festive, we can even align it to a specific column. This is achieved by string manipulation, which I might explain in a later post.
@ECHO OFF
FOR /F %%a IN ('DIR /B /A:D') DO CALL :DISPLAY "%%a"
GOTO :END
:DISPLAY
SET MYVAR=                    %~1
SET MYVAR=%MYVAR:~-20%
ECHO %MYVAR% - Check.
GOTO :eof
:END

Add a comment

HTML code is displayed as text and web addresses are automatically converted.

This post's comments feed