1

I have to modify existing shell scripts and they start with

#!/bin/sh

What reason would someone use that on a system that also supports bash? I am tempted to change it but I want to make sure there's not a reason I don't know of for this.

My current problem is with a string manipulation and using ${mystring:start:length} would be so easy in bash but not avail in sh.

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255
Mario
  • 63
  • If you don't care for portability and speed, go ahead and use the language you're more familiar with. – pLumo Apr 06 '20 at 14:49
  • 2
    Do NOT modify them. Write your own scripts from scratch, in whatever language you're most familiar with. Using bash instead of sh as if they were the same does not always results in obvious errors, it may also SILENTLY result in (potentially catastrophic) different behavior. The most obvious case is cmd &> file which is valid in both sh and bash, but do a completely different thing. –  Apr 06 '20 at 15:02

1 Answers1

4

It may be not obvious these days, when modern linux distributions are most common operating systems, but some time ago you could find not only variuous systems not having bash at all, but as I recall even one linux distribution, which in one of its versions had /bin/bash linked to some not Bourne-like shell.

Moving #!/bin/bash scripts from one system to another was annoying back then, so it was wiser to script in pure bourne shell without bashisms.

So portability was the main reason I guess. I still use #!/bin/sh if I am sure there won't be any bashisms in the script, although it's been at least ten years since there is nothing else than linux around me.

  • I'm not quite sure, but you seem to assume that all Linux distributions use bash as /bin/sh, which is definitely not the case. – Kusalananda Apr 06 '20 at 15:56
  • 1
    There are still environments without bash. Some recovery shells don't give access to bash, but certain scripts still need to work even then. Busybox uses ash, which doesn't support some bash features. Some embeded environments only include sh or similar to save space. Portability can still be a concern... not for you and me... but for a distro developer or software packager? They have to think long and hard about even the slightest chance their scripts wont run in cases they want to support. – Cliff Armstrong Apr 06 '20 at 16:20
  • Kusalananda: Not exactly. I assume that most linux distributions has /bin/bash, but not necessarily as /bin/sh. So today one can call /bin/bash and it will hardly fail. But not all systems had bash whatsoever, that is why it was better to call /bin/sh and make a portable script without bash specific syntax, than to call /bin/bash and get execution errors on those systems. On the other hand there were many scripts on linux (third party software mostly), that called /bin/sh using bashisms. That was even worse. – lakukaracza Apr 06 '20 at 16:39