Windows batch special characters cheat sheet
Operators, variables and STDERR redirection in cmd batch scripts.
Reference of the special characters and variables used in Windows batch (cmd) scripts, plus a note on redirecting standard error.
Special characters
| Character | Meaning |
|---|---|
& |
Separates commands on a line. |
&& |
Runs the next command only if the previous command's errorlevel is 0. |
|| |
Runs the next command only if the previous command's errorlevel is not 0. |
> |
Output to a file. |
>> |
Append output to a file. |
< |
Input from a file. |
| |
Output of one command piped into the input of another. |
^ |
Escapes any of the above, including itself, when it must be passed to a program. |
" |
Parameters containing spaces must be enclosed in quotes. |
+ |
With copy, concatenates files, e.g. copy file1+file2 newfile. |
, |
With copy, indicates missing parameters. Updates the modified date, e.g. copy /b file1,,. |
Variables
| Syntax | Meaning |
|---|---|
%variablename% |
Built-in or user-defined environment variable. |
!variablename! |
User-defined variable expanded at execution time; requires SetLocal EnableDelayedExpansion. |
%<number> (%1) |
The nth command-line parameter passed to the batch file. %0 is the batch file name. |
%* |
The entire command line. |
%A or %%A |
Loop variable of a for loop: a single % at the command prompt, a double %% in a batch file. |
Redirecting standard error
The order of the redirections matters. The first form does not redirect STDERR to the file, the second does:
REM *** WARNING: THIS WILL NOT REDIRECT STDERR TO STDOUT ****
dir 2>&1 > a.txt
dir > a.txt 2>&1
The code page can be switched with chcp 437 when output characters are garbled.