Create multi-platform #CLI script for #Windows, #Linux & #MacOSX

Do you need to make run script which will work on multiple platforms? You can use my idea. In my case it’s run script which runs Java application and you can found it here. Interested in how it works?

How it works?

It is based on different line-braking between Windows and Unix and bash presence on Unix systems. It also expects that Unix systems has not GOTO command and don’t stop on error.

#!/bin/bash
^M
GOTO Windows^M

# Unix
ls
exit
^M
:Windows^M
dir^M
exit^M

The file must contains these parts:

  1. #!/bin/bash for Unix to determine how to execute this file
  2. An empty line for Windows to explode lines
  3. GOTO Windows for Windows to skip Unix lines
  4. An Unix code and exit
  5. An empty line for Windows to explode lines
  6. :Windows anchor for Windows
  7. A Windows code and exit

Don’t forget that Unix lines must end with \n, but Windows lines must end with \n\r (^M in example).