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 /bin/sh?
Testing specific capabilities of the current interpreter is a different issue, and e.g. bash offers $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 ...
Use a #! ("shebang" or "hashbang") line.
A #!-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.
A bash script may have
#!/bin/bash
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,
#!/usr/bin/env bash
as its first line, for example.
This ensures that it will always be interpreted by bash and not by sh or csh or 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
./myscript
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.
shandcsh. – JdeBP Mar 13 '19 at 18:25#!-line in the script? This is never an issue with e.g. Perl, Python or Ruby scripts, so it shouldn't be an issue for a script written for some other interpreter. – Kusalananda Mar 13 '19 at 18:54