Thanks for all the input. I will try to answer my own question now and provide a complete guide to the different possibilities to execute scripts and binaries. Please edit and comment and we'll be able to come up with something that is complete and correct. Here's my suggestion:
At first, two points to state:
Linux makes a distinction between a command and a path. A command is only typed as-is on the prompt, and will execute a built-in or will cause Linux to look for a corresponding binary or a script on the $PATH.
For Linux to interpret something as a path, it needs to contain at least one slash (/). E.g. in
./ can seem pretty redundant - it's there only to make Linux interpret it as a path rather than a command.
So, the options for executing a binary or a script:
Executing a binary
$ binary # when 'binary' is on the PATH, or is a built-in
$ ./binary # when 'binary' is not on the path but in the current directory
$ /home/me/binary # when 'binary' is not on the PATH, and not in the current dir
Executing a script
The file will have to have execute permissions unless stated otherwise.
$ script # execute a script that is on PATH. Will be executed in a new shell.
# The interpreter to use is determined by the she-bang in the file.
$ ./script # execute a script that is in the current dir. Otherwise as above.
$ /a/dir/script # when the script is not on the PATH and not in current dir.
# Otherwise as above.
$ . script # execute a script in the current dir. Will be executed in the
# current shell environment.
$ source script # equivalent to the above *1
$ sh script # executes 'script' in a new shell *2 (the same goes for 'bash ...',
# 'zsh ...' etc.). Execute permission not neccessary.
Scripts with a she-bang (e.g.
#!/bin/sh) on the first line tells which interpreter to use.
- This interpreter will be used when executed by
./script or using a command:
script must be on the PATH)
sh script will ignore the she-bang and use, in this case,
sh as the interpreter
. script or
source will ignore the she-bang and use the current interpreter (since
source is equivalent to just executing each line of the script in the current shell)
*1: This is only almost true. In bash they are indeed the same command, but when using
script will be searched for in $PATH before the current dir. That's bash, but in POSIX-only shells,
source doesn't work, but
. does. So rather use the latter for portability.
*2: what actually happens is that we run the binary sh with 'script' as argument, which will make 'sh' execute 'script' in its new shell