Batch Files
From DesigningPatterns
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
setcommands. The correct format is:
set foo=bar
- Do *NOT* use
set varunless you have really good reason to do so, as you will conflict with environment variables. - Do wrap your code in
setlocalandendlocalto prevent polluting the environment.
References
- This site has lots of good information, especially concerning when particular batch file features were introduced.
- Batch file tricks
- Command-line arguments
- This covers the
cmdswitches (arguments).
