10

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
  • 826
  • 2
  • 12
  • 27

2 Answers2

22

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
  • 6,249
  • 6
  • 28
  • 36
  • Thanks. Exactly what I was looking for. I'd be interested, though, if there are other ways. – wehnsdaefflae Apr 30 '15 at 16:14
  • You can modify the first line to `@rem(){ :;};@rem '` to make this line silent on Windows. A similar idea is presented here https://danq.me/2022/06/13/bash-batch/ – insaneinvader Jun 18 '23 at 08:56
-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
  • 6,121
  • 1
  • 16
  • 26