Skip to content

Instantly share code, notes, and snippets.

@booyaa
Last active December 26, 2015 04:59
Show Gist options
  • Save booyaa/7097688 to your computer and use it in GitHub Desktop.
Save booyaa/7097688 to your computer and use it in GitHub Desktop.
dos batch magick

#ERROR redirection

:: redirect stderr to nul
dir *.csv 2> NUL

:: in a batch file for loop, you may need to escape the char
for /f "delims=" %%x in ('dir *.csv 2^> NUL') do @echo %xx

#EXISTS

IF EXISTS SOMEDIRECTORY\NUL ECHO SOMEDIRECTORY exists

#FOR command

inline

FOR /F %F IN ('dir /b') DO @ECHO %F

#FOR filemask

inline/dos prompt

FOR %F IN ("*.txt") DO @ECHO %F

batch file

FOR %%F IN ("*.txt") DO (
  ECHO %%F
  ECHO other shit...
)

#FOR lists

I find this tends to be more useful for irregular lists i.e. mixed values or out of sequence integers

dos prompt

FOR %F IN (100 121 FOO BAR) DO @ECHO %F

#GOTOs and labels

@ECHO OFF
GOTO END

:END
ECHO FIN!

#IF

SET FOO="bar"
IF "%FOO%" == "bar" GOTO THIS

Note there's no != or <> you need to prefix a negative i.e. NOT "%FOO%" == "bar"

#Logging out batch statements

(ECHO hello
ECHO world) >> useful.log
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment