Single script to run in both Windows batch and Linux Bash?

后端 未结 11 1891
盖世英雄少女心
盖世英雄少女心 2020-11-28 19:04

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

11条回答
  •  情深已故
    2020-11-28 20:00

    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
    
    • The first line does echo off in cmd and doesn't print anything on sh. This is because the @ 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.
    • The second one defines ::, 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.
    • Now I can prepend sh commands with :: and they are ignored in cmd
    • On :: exit the sh script ends and I can write cmd commands
    • Only the first line (shebang) is problematic in cmd since it will print command not found. You have to decide yourself if you need it or not.

提交回复
热议问题