I was looking up shebang and wondering why I would use it. I could execute a bash script using:
(with a shebang line in foo.sh)
What are the pros and cons of each and which one should I use by default?
I would say yes, it's intrinsically better to use a shebang.
If you put all your scripts in your
~/bin) and mark them as executable, then you can execute them by name without thinking about which interpreter you need to invoke (bash, Python, Ruby, Perl, etc.).
If you place an executable file named
foo with a shebang anywhere in your
$PATH, you can simply type
foo to execute it.
You have to type
#!/bin/bash at the top and
chmod +x the file.
This is near-zero cost for a very convenient return.
The main reason for using a hashbang is specifying the exact interpreter you want to use. While writing portable shell scripts is nice, one often relies on some features of a particular shell (the word "bashism" has a foundation in the real world) and thus it is desirable to make clear what should be the interpreter.
It is also not limited to shell scripts only - in anything but a shell script the hashbang is a must, otherwise the system won't know what to do with the file and will try to interpret the script with user's default shell. Which usually is not the desired operation for AWK, Perl, Python, Ruby, Tcl/Tk... you name it. AWK is actually another example of why the hasbang is important - there are subtle differences between various implementations, and requiring a specific interpreter might be a good way to prevent unexpected disappointments. The same holds for Python scripts that are version 2/3-only.