9

I noticed that Windows 7 enables to execute .sh files as if they were .bat files. That got me wondering whether it is possible to write a .sh file such that it can be executed in Windows and Linux (let's say bash).

The first thing that comes to my mind is to fabricate an if-statement such that Windows and Ubuntu can deal with it and jump into the according block to execute plattform-specific commands. How could this be done?

Note: I know this is not good practice. I also know that scripting languages like Python are far better suited to solve this problem than a mixed-syntax command line script would be. I'm just curious...

wehnsdaefflae
  • 728
  • 1
  • 10
  • 25

2 Answers2

19

You could use this:

rem(){ :;};rem '
@goto b
';echo sh;exit
:b
@echo batch

It's valid shell script and batch, and will execute different blocks depending on how it's run.

Modify the echo and @echo lines to do what you want.

Biffen
  • 5,791
  • 5
  • 29
  • 34
-1

AFAIK, you can't directly run .sh files from Windows' cmd.exe. For that you'll need a *nix emulation layer to run the shell. Check out Cygwin or Msys/MinGW

dekkard
  • 4,015
  • 1
  • 14
  • 25