Aug 17, 2008

Batch Programming Tricks --- 3

Exit a batch file w/o error message or orphaned file.
This method does not leave a 0 byte file behind, but uses pipes so it writes to %temp% or current. This trick courtesy of Laura Fairhead, http://lf.8k.com/.
CTTY NUL |GOTO |CTTY CON |CALL ECHO ON

Use FOR to process GOTO's.
FOR does not see the colon as a delimiter, but GOTO does. Therefore, they can be used together.
IF "%1"=="" FOR %%v IN (ECHO GOTO:end) DO %%v parameter required

Suppress screen messages, including error messages.
:: test.bat
@ECHO off
CTTY nul
ECHO this is a test
DIR/AD \..\
CTTY con

Selectively display messages when screen output is suppressed.
:: test2.bat
@ECHO off
CTTY nul
ECHO This message will not be displayed
ECHO This message will be displayed >con
CTTY con

Delete all non-system, hidden or read-only files without confirmation.
DEL c:\dirname\*?.*

Use the pipe to place separate commands on one line.
Commands can sometimes be combined on one line.
SET |FIND.EXE "windir" |IF errorlevel=1 ECHO Windows not running
:: Here are six commands on one line:
D:|CD\|DIR/AD/-P TEMP|FIND "TEMP "|IF not errorlevel=1 CD TEMP

Delete all files in a directory, regardless of attributes.
This example uses the pipe to place separate commands on one line. Be careful with this one, don't do anything rash.
ATTRIB.EXE -R -A -S -H DirName\*.* |ECHO Y |DEL DirName\*.* >nul

Multiple pipes, and an ansi trick.
Ansi.sys required; Esc represents the escape character, created in edit by 'Ctrl+P Esc'
::howmany.bat
@ECHO off
:: display how many files and bytes in current and sub-directories
DIR/A-D/W/S/-P |FIND "file(s)" |SORT/R |FIND/N "file(s)" |FIND "[1]"
IF not errorlevel=1 ECHO Esc[1ATotal:

Place comments on a command line.
ATTRIB.EXE, %1 %removes file attributes - broken in MS-DOS 7.x%

Echo pipes and redirection characters to the screen or to another file.
ECHO @PROMPT a+b $g c+d$_ > %temp%.\spchar1.bat
COMMAND/E:2048/C %temp%.\spchar1.bat |FIND "+" >%temp%.\results.txt
DEL %temp%.\spchar1.bat

Echo pipes and redirection characters with a single command.
Use %v at the prompt and %%v in a batch file.
COMMAND/E:2048/CFOR %v IN (1 2) DO PROMPT a+b $G c+d $_ |FIND/V "PROMPT">results.txt

1 comment:

johny radio said...

the following batch file is producing "File Not Found" in my output. i have read that CTTY NUL is not supported on Windows Vista. how to suppress errors in a Vista batch file? -thanks

@echo off
CTTY NUL
del temps.txt
for /r /d %%d in (*) do dir "%%d\temp"
CTTY CON