I know it, forgets it and relearn it again. Time to write it down.
To start the shell-script 'file.sh':
sh file.sh
bash file.sh
Another option is set executable permission using chmod command:
chmod +x file.sh
Now run .sh file as follows:
./file.sh
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
).
If you want the script to run in the current shell (e.g. you want it to be able to affect your directory or environment) you should say:
. /path/to/script.sh
or
source /path/to/script.sh
Note that /path/to/script.sh
can be relative, for instance . bin/script.sh
runs the script.sh
in the bin
directory under the current directory.