Finding bash Portably for #!

Problem

You need to run a bash script on several machines, but bash is not always in the same place. See Getting bash for xBSD.

Solution

Use the /usr/bin/env command in the shebang line, as in #!/usr/bin/env bash. If your system doesn’t have env in /usr/bin, ask your system administrator to install it, move it, or create a symbolic link because this is the required location. For example, Red Hat inexplicably uses /bin/env, but they at least create a symlink to the correct location.

You could also create symbolic links for bash itself, but using env is the canonical and correct solution.

Discussion

env’s purpose is to “run a program in a modified environment,” but since it will search the path for the command it is given to run, it works very well for this use.

You may be tempted to use #!/bin/sh instead. Don’t. If you are using bash-specific features in your script, they will not work on machines that do not use bash in Bourne shell mode for /bin/sh (e.g., BSD, Solaris, Ubuntu 6.10+). And even if you aren’t using bash-specific features now, you may forget about that in the future. If you are committed to using only POSIX features, by all means use #!/bin/sh (and don’t develop on Linux, see Developing Portable Shell Scripts), but otherwise be specific.

You may sometimes see a space between #! and /bin/whatever. Historically there were some systems that required the space, though in practice we haven’t seen one in a long time. It’s very unlikely any system running ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.