Windows Batch (CMD) is probably the least suitable language for code golfing.
Avoid newline characters. If you're looking for the shortest code in bytes, as opposed to characters, you will want to get rid of all unnecessary carriage returns (newline characters = 2 bytes). You can use the &
operation to do this, trimming one byte for each command.
echo Hello&echo World.
Setting variables. When setting variables using switches, the set
parser will ignore spaces.
set /a a+=1
set /p b="User Input: "
:: Will be handled the same as..
set/aa+=1
set/pb="User Input: "
Note that the same parser rules do not apply to all commands - as an example, for loops require spaces. Except between the set, string, or command
(i.e. what is inside the brackets) and the word do
.
for /f %%a in (file.txt)do ...
Simple mathematical expressions. Also, notice the expression that I used for incrementing in the set /a
command. For simple mathematical expressions use += -= *= /=
instead of (for example) set /a a=%a%+1
.
Gathering command output. To get the output of a command, it can sometimes be useful to output to and read from a file, where you otherwise might have used a for loop to gather the output:
for /f %%a in ('echo test') do set a=%%a
:: Can be shortened to
echo test>f&set/pa=<f
echo test
send stdout to a file called f, >f
, start a new command &
and get the contents of the file in a variable set/pa=<f
. Obviously this isn't always useful. But it can be when all you need is a single line of output.
Command output. When suppressing command output, use @
before the commands, unless you need to suppress more than 9 commands, in which case, use @echo off
at the start of your script. @echo off
is 9 bytes long, and therefore will generally save more bytes with longer scripts.
Commands often do more than just what is obvious - think about what your commands are doing. For example; if you need to set a variable and echo another variable, instead of:
set a=OUTPUT
echo %a%
echo test>f
set /p b=<f
You can use the set command with the /p
switch to output %a%
for you.
set a=OUTPUT
echo test>f
set /p b=%a%<f
Completely golfed...
set a=OUTPUT&echo test>f&set/pb=%a%<f
A couple of expamples - Count sum of all digits - Goldbach's conjecture.
Any other tips are more than appreciated - I'll keep updating this if I think of anything else.