Batch Files

From DesigningPatterns

Jump to: navigation, search

Contents

Background

Batch files are the DOS/Windows answer to shell scripts. They have a bad reputation and indeed, they can be quite gnarly. On the other hand, they provide roughly the same functionality as does the Bourne Shell's scripting language, and can be useful for small scripts.

Techniques

Exiting with an Exit Code

cmd /d /c exit /b %exit_code%

where exit_code is a variable containing the exit code. To print out the last exit code on the command do, do:

echo %errorlevel%

The errorlevel variable is predefined.

Batch File's Directory

echo %~dp0

The ~dp0 predefined variable contains a batch file's directory, allowing the batch file to use paths relative to itself rather than the current working directory.

Warnings

  • Do *NOT* put a space between in set commands. The correct format is:
set foo=bar
  • Do *NOT* use set var unless you have really good reason to do so, as you will conflict with environment variables.
  • Do wrap your code in setlocal and endlocal to prevent polluting the environment.

References

Personal tools