Given a shell script file that begins as
#!/bin/bash
# (bash script here),
and has been chmod +xed, is there any difference in running ./script and bash script from the command-line?
Given a shell script file that begins as
#!/bin/bash
# (bash script here),
and has been chmod +xed, is there any difference in running ./script and bash script from the command-line?
It depends on your $PATH. ./script will run /bin/bash script. bash script will use whatever bash comes first in your path, which isn't necessarily /bin/bash, and could be a different version of Bash.
There are two differences:
./tryit.sh will not run if bash is not located in /bin, but bash tryit.sh will run if bash is anywhere on your PATH. This is because ./tryit.sh will use the shell from the bang path (/bin/bash), but bash tryit.sh will use the first bash shell on the PATH. ./tryit.sh will not run if the execute bit is not set, but bash tryit.sh will run the script. You have excluded this case by specifying the bit has been set. Some edits may clear the bit causing a working command to start failing.The command bash tryit.sh invokes bash telling it that the commands to be executed are found in the file tryit.sh. Many programs such as awk, perl, python, bash, sh, ksh, work in this manner. This is a standard idom for Unix programs that process command files.
They are subtly different and easy to make a mistake.
The one you should use (which I'll write in two forms)
./script
bash ./script
My reasoning is that this is explicit, in case you've changed directory.
non explicit forms
script
bash script
Are less safe. bash script will search the current directory then the directories in the PATH environment variable, script by itself is searched only in PATH directories. Running a different command than intended could clobber your files.
If I remember correctly from the top of my head, the following two are identical:
$ ./script
and
$ source script
So using the ./ "command" will in fact invoke source under the hood, which on its part is a bash builtin command. Or, in another interpretation they might be called aliases of each other.
However: The first invocation requires you, the user, to set the +x (=executable) flag with chmod for owner or group, otherwise you will get a "permission denied" error, whilst execution using the source command is even possible without the +x flag. So the latter will sometimes be your life-saver whenever you want to run a bash script off an NTFS-formatted pendrive, for instance, since chmod cannot work there.
I think that will answer your question as well in some way.
Because, for that reason, bash script and source script cannot be exactly the same; the one is calling the bash program itself with your script given as a parameter, whilst the other is calling one of bash's builtin commands with your script as a parameter.
Though the result will most probably be the same (at least in everyday use), the ways how to get there are somewhat different in both cases.