4
\$\begingroup\$

Enabling delayed expansion variables in Batch chews up a lot of bytes. The shortest I have managed to make it is:

@!! 2>nul||cmd/q/v/c%0&&exit/b

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>null becomes 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 @ and /q)..

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)

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Good, not only will this help people with their golfing, but it will stop people from Stack Overflow getting annoyed with us :) \$\endgroup\$
    – Beta Decay
    Aug 4, 2015 at 11:17
  • 1
    \$\begingroup\$ Questions about golfing specific code snippets are on topic. \$\endgroup\$
    – Jwosty
    Aug 5, 2015 at 19:26
  • \$\begingroup\$ for some reason, using this in some scripts tend to execute the script twice... \$\endgroup\$
    – ScriptKidd
    Apr 19, 2020 at 11:21

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.