An individual script should not have to test what interpreter it's running in. That kind of introspection is awkward and error prone and would possibly have to be implemented differently for different Unices.
For example, a Perl script can always safely assume that it's being interpreted by a Perl interpreter, a Python script is always run by a Python interpreter, and so on. So why should not a
bash script assume that it's being run by
bash, and an
sh script that it's being run by
Testing specific capabilities of the current interpreter is a different issue, and e.g.
$BASH_VERSION and the
$BASH_VERSINFO array to test a version against (for example).
So how can you make e.g. a
bash script be run by
bash and a
csh script be run by
csh? Well, you avoid letting the user pick the interpreter.
You can do that by
Not putting a filename suffix on the script file, in case that would "confuse" the user. A
bash script in a
myscript.sh file might make the user think it would be runnable with
sh. Instead, just call the script
myscript, and ...
#! ("shebang" or "hashbang") line.
#!-line goes on the very first line of the script (the two characters
#! have to be the first in the file) and specifies the path to the interpreter to use.
bash script may have
if that's the path to the
bash executable on your system, or if you want
bash to be picked up from wherever in
$PATH it's located on your system it could have,
as its first line, for example.
This ensures that it will always be interpreted by
bash and not by
python or some other unrelated language interpreter.
The next step would be to
- Make the script executable, using
chmod +x myscript.
Now you can run your script with
without bothering with what interpreter to use for executing it. In fact, to the user of the script, it would not matter at all whether it was a
bash script, a Python script, or a compiled binary.