How To Use Shebang At Top of Shell Script to Set Language
Normally, any line in a shell script that begins with a
# is assumed to be a comment. The only exception to that is if it is the first line, and is
#! followed by the program you want to use as an interpreter to the shell script.
Normally you will see something like this:
The reason to do this is that someone might be using a different shell but you want to make sure they use the right one, otherwise the script will fail.
BUT what if you installed a newer version of
/usr/local/bin/perl and want to use that one instead of the one at
Well, you could change all of your scripts to use
#!/usr/local/bin/perl but then if you are on a Mac which does not have
/usr/local/bin/perl installed, it will fail.
That is where
env comes in.
#!/usr/bin/env FOO you are telling the script, “Use whichever version of FOO that you find first in the
So if your if
PATH looks like this
env will look at
/usr/local/bin first, and then
/usr/bin and so on. As soon as
FOO is found in one of those folders, it will be used.
So, while I expect most of my
zsh scripts will be used by people who only have
/bin/zsh, because I use
env I can use
(The only thing you have to be careful about is that if you use any features that have been added to
/usr/local/bin/zsh but are not in
/bin/zsh then you should specify
Portability Is Hard…
In an ironic twist, when I used to have a shell account on a Linux box, changing my
zsh scripts to start with
#!/usr/bin/env zsh failed because that version of Linux had
/bin/env instead. Yet another reason I'm happy to have server be with Mac Stadium now.
“How do I tell which shell I’m using?”
If you have a shell script that works but you are not sure which shell is running it, add the line:
to the script and it will tell you, e.g.
/bin/zsh or whatever.