user3053247
user3053247

Reputation:

What are all options to execute and source a bash file? Why shebang is not checked?

I have a bash file and I see that I can do on it the following:

./file.sh               >> executes the file following the chmod -x file.sh rule
bash ./file.sh          >> executes the file 
bash file.sh            >> executes the file 
source ./file.sh        >> source the file code
file                    >> source the file code

Am I correct in the interpretation or wrong? I hear that there is something "PATH" related, but I don't know about.

Also, as far as I am seeing the shebang/hashbang is not always checked. Why not? This is an example I am using: #!/bin/echo "This script should be sourced in a shell"

Any insights would be good; as I am few weeks old to bash.

Upvotes: 0

Views: 251

Answers (1)

that other guy
that other guy

Reputation: 123470

Your interpretation is a bit off:

./file.sh               >> executes the file with its requested interpreter
bash ./file.sh          >> executes the file with bash, no matter which language it is
bash file.sh            >> executes the file with bash, no matter which language it is
source ./file.sh        >> sources the code in the current shell
file                    >> executes the file from PATH with its requested interpreter

By default you should always use ./file.sh (if it's in the current directory) or file (if it's renamed and put in a directory in PATH), since that way it can be a Python script or Ruby script or C binary and it doesn't matter.

Upvotes: 3

Related Questions