Is it possible to write a single script file which executes in both Windows (treated as .bat) and Linux (via Bash)?
I know the basic syntax of both, but didn\'t figu
I use this technique to create runnable jar files. Since the jar/zip file starts at the zip header, I can put a universal script to run this file at the top:
#!/usr/bin/env sh\n
@ 2>/dev/null # 2>nul & echo off & goto BOF\r\n
:\n
exit\n
\r\n
:BOF\r\n
\r\n
exit /B %errorlevel%\r\n
}
It is important to set the line endings as outlined above because they can cause issues on the different platforms. Also the goto statement will not work correctly in some cases if the proper line endings are missing around the jump label.
The technique above is what I use currently. Below is an outdated version with an in-depth explaination:
#!/usr/bin/env sh
@ 2>/dev/null # 2>nul & echo off
:; alias ::=''
:: exec java -jar $JAVA_OPTS "$0" "$@"
:: exit
java -jar %JAVA_OPTS% "%~dpnx0" %*
exit /B
@
in sh throws an error that is piped to /dev/null
and after that a comment starts. On cmd the pipe to /dev/null
fails because the file is not recognized on windows but since windows doesn't detect #
as a comment the error is piped to nul
. Then it does an echo off. Because the whole line is preceded by an @
it doesn't get printet on cmd.::
, which starts a comment in cmd, to noop in sh. This has the benefit that ::
does not reset $?
to 0
. It uses the ":;
is a label" trick.::
and they are ignored in cmd:: exit
the sh script ends and I can write cmd commandscommand not found
.
You have to decide yourself if you need it or not.