Executing a script
Mar 15 2010 ยท Random
Possibly the best explanation ever on how to execute a *nix script:
To run a non-executable sh script, use:
sh myscript
To run a non-executable bash script, use:
bash myscript
To start an executable (which is any file with executable permission); you just specify it by its path:
/foo/bar /bin/bar ./bar
To make a script executable, give it the necessary permission:
chmod +x bar ./bar
When a file is executable, the kernel is responsible for figuring out how to execte it. For non-binaries, this is done by looking at the first line of the file. It should contain a hashbang:
#! /usr/bin/env bash
The hashbang tells the kernel what program to run (in this case the command /usr/bin/env is ran with the argument bash). Then, the script is passed to the program (as second argument) along with all the arguments you gave the script as subsequent arguments.
That means every script that is executable should have a hashbang. If it doesn’t, you’re not telling the kernel what it is, and therefore the kernel doesn’t know what program to use to interprete it. It could be bash, perl, python, sh, or something else. (In reality, the kernel will often use the user’s default shell to interprete the file, which is very dangerous because it might not be the right interpreter at all or it might be able to parse some of it but with subtle behavioural differences such as is the case between sh and bash).