This is an extract from the manual (
If command line arguments besides the options have been specified,
then the shell treats the first argument as the name of a file from
which to read commands (a shell script), and the remaining arguments
are set as the positional parameters of the shell ($1, $2, etc).
Otherwise, the shell reads commands from its standard input.
sh file.sh the specified file
file.sh becomes an input source for the shell, so needs to be readable, but need not be executable. The same is true of the
. command, so the following will all run a non-executable file:-
The last two will execute in the current shell, the first two in a sub-shell. Note that
sh -c ./file.sh will require
file.sh to executable, while
sh -c ". ./file.sh" needn't. Note also that if
file.sh is executable, then its location needs to be in
$PATH if it is called directly, unless a specific path (
./ in the example) is included:
However, the four previous examples do not need the
./ prefix, as the file to read will always be sought in the current directory (though the
source commands will also search
Two final points:-
- The four examples work only for script files: they will all fail if
file.sh is a binary executable.
- In the four examples, the
#!/bin/bash comment is just a comment: the executing
sh will read it as such and will not clone
bash to execute the rest of the file, so any
bash extensions in it will cause errors.