Enabling delayed expansion variables in Batch chews up a lot of bytes. The shortest I have managed to make it is:
Saving 11 bytes over
@echo off&setLocal enableDelayedExpansion. The method is explained here - Tips for Golfing in Batch. Basically, it runs a command (
!!) which fails initially (due to no delayed expansion) causing the script to be called again with delayed expansion variables enabled and echo turned off. The command (which is expanded now to 'nothing') then executes successfully, causing the rest of your script to be run. The initial instance of the script then exits.
Can this be made any shorter / better? If so, how?
One way which I have thought to make it smaller is piping the error output to a file with a one character name, instead of to null (
2>f). However, you then run the risk of overwriting an existing file, as well as generating unwanted output in the form of a file containing the error:
'!!' is not recognized as an internal or external command, operable program or batch file.. Which I suppose is fine if the challenge doesn't specify output requirements (in which case you can probably drop the redirect all together along with
Suppressing no output you can save a further 9 bytes:
!!||cmd/v/c%0&&exit/b. And in fact, you could drop the exit and just have the code run again without delayed expansion variables enabled (it won't run correctly the second time, but it will have already run). So if output doesn't matter, you could do something like the following:
!!||cmd/v/c%0 set a=test echo !a!
Which would output:
h:\>test.bat h:\>!! || cmd/v/ctest.bat '!!' is not recognized as an internal or external command, operable program or batch file. h:\>!! || cmd/v/ctest.bat h:\>set a=test h:\>echo !a! test h:\>set a=test h:\>echo !a! !a!
(Inspired by Golfing with Python Import)