When you are creating a new shell script, you want to make sure it is as problem free as possible, but sometimes it can be a bit confusing to know which shebang is the best one for you to use. On that note, today’s SuperUser Q&A post has the answer to a confused reader’s question.
Today’s Question & Answer session comes to us courtesy of SuperUser—a subdivision of Stack Exchange, a community-driven grouping of Q&A web sites.
SuperUser reader Hendre wants to know when it is better to use #!/bin/bash instead of #!/bin/sh in shell scripts:
When is it more appropriate to use #!/bin/bash rather than #!/bin/sh in a shell script?
When is it better to use #!/bin/bash instead of #!/bin/sh in a shell script?
SuperUser contributor grawity has the answer for us:
- There are several shells which implement a superset of the POSIX sh specification. On different systems, /bin/sh might be a link to ash, bash, dash, ksh, zsh, etc. It will always be sh-compatible though, never csh or fish.
- As long as you stick to sh features only, you can (and probably even should) use #!/bin/sh and the script should work fine, no matter which shell it is.
- If you start using bash-specific features (i.e. arrays), you should specifically request bash because, even if /bin/sh already invokes bash on your system, it might not on everyone else’s system, and your script will not run there. The same applies to zsh and ksh, of course.
- Even if the script is for personal use only, you might notice that some operating systems change /bin/sh during upgrades. For example, on Debian it used to be bash, but was later replaced with the very minimal dash. Scripts which used bashisms but had #!/bin/sh suddenly broke.
- Even #!/bin/bash is not that correct. On different systems, bash might live in /usr/bin, /usr/pkg/bin, or /usr/local/bin.
- A more reliable option is #!/usr/bin/env bash, which uses $PATH. Although the env tool itself is not strictly guaranteed either, /usr/bin/env still works on more systems than /bin/bash does.
Have something to add to the explanation? Sound off in the comments. Want to read more answers from other tech-savvy Stack Exchange users? Check out the full discussion thread here.
Image Credit: Wikipedia