There are three general ways to run a script file in Bash: sourcing it, providing it to bash as input, and as a standalone script. For the following examples, we'll use the hello.bash script, with the following contents:
printf 'Hello, %s!\n' "$USER"
Sourcing the script means to use the Bash source command to read all of the commands in a script into the current shell session and run them there. A source command to read in a script such as hello.bash might look like this:
bash$ source hello.bash Hello, bashuser!
This method behaves rather like a function, in that it runs the commands as if you had entered them from your own shell. Variable settings, directory changes, shell options, and other changes will apply to the current running shell session. This may not necessarily be what you want—more often than not, you will want the script to do its work, and then exit and leave you back at your shell session without changing any of your settings.
To avoid this, we can also provide the script to bash explicitly as input. You can either call the bash program with the script name as an argument, or provide it as input with a pipe or redirection:
bash$ bash hello.bash Hello, bashuser! bash$ cat hello.bash | bash Hello, bashuser! bash$ bash < hello.bash Hello, bashuser!
This starts a new Bash subprocess, which runs the commands in the file, and then exits.
However, this method requires us to know that bash is the interpreter for the program, and means the command has at least two parts. Someone else using our script may not care what language it works in; they just want to run it! It would therefore be convenient to be able to just run the script directly, using only its name, which the next section explains.