Skip to content

Instantly share code, notes, and snippets.

@co89757
Last active November 19, 2017 00:30
Show Gist options
  • Save co89757/bffc7c51e80776508ea22f69e9ab1b8c to your computer and use it in GitHub Desktop.
Save co89757/bffc7c51e80776508ea22f69e9ab1b8c to your computer and use it in GitHub Desktop.
batch scripting
@ECHO OFF
REM turn this on to enable loop-scope variable expansion (at exec time, rather than parse-time)
SETLOCAL ENABLEDELAYEDEXPANSION
SET me=%~n0
SET parent=%~dp0
::======= HEADER END =====
REM gotcha: to set variables whose value contain spaces
SET 'V=I HAVE SPACE'
ECHO %V%
::==== check error code of commands ==
SomeFile.exe
IF %ERRORLEVEL% NEQ 0 (
REM address the error here
)
::=== return error code on execution fault
SomeCmd.exe || EXIT /B 1
:: OR
someCmd.exe || GOTO :EOF
::=== IF/FOR SECTION======
IF EXIST "temp.txt" (
ECHO found
) ELSE (
ECHO not found
)
::It’s a good idea to always quote both operands (sides) of any IF check. This avoids nasty bugs when a variable doesn’t exist, which causes the the operand to effectively disappear
IF "%VAR%"=="" ( SET VAR=DEFAULT )
:: check if a variable matches a text case-insensitively
IF /I %VAR%=="HELLO" ( ....)
::======= FUNCTIONS (using CALL and labels) ======
REM GOTCHA:
REM Your quasi functions need to be defined as labels at the bottom of your script.
REM The main logic of your script must have a EXIT /B [errorcode] statement. This keeps your main logic from falling through into your functions.
::===== AN EXAMPLE ===
@ECHO OFF
SETLOCAL
:: script global variables
SET me=%~n0
SET log=%TEMP%\%me%.txt
:: The "main" logic of the script
IF EXIST "%log%" DELETE /Q %log% >NUL
:: do something cool, then log it
CALL :tee "%me%: Hello, world!"
:: force execution to quit at the end of the "main" logic
EXIT /B %ERRORLEVEL%
:: a function to write to a log file and write to stdout
:tee
ECHO %* >> "%log%"
ECHO %*
EXIT /B 0
REM END OF THE EXAMPLE
::===== READ USER INPUT AND CONFIRM ===
:confirm
SET /P "Continue [y/n]>" %confirm%
FINDSTR /I "^(y|n|yes|no)$" > NUL || GOTO: confirm
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment