5

I was looking up shebang and wondering why I would use it. I could execute a bash script using:

bash foo.sh

or

./foo.sh

(with a shebang line in foo.sh)

What are the pros and cons of each and which one should I use by default?

Lee Kang
  • 153

2 Answers2

7

I would say yes, it's intrinsically better to use a shebang.

Pro:

If you put all your scripts in your $PATH (maybe /usr/local/bin or ~/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.

Con:

You have to type #!/bin/bash at the top and chmod +x the file.

This is near-zero cost for a very convenient return.

peterph
  • 30,838
nanny
  • 296
1

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.

peterph
  • 30,838
  • It's not always the exact interpreter to be used, with #!/usr/bin/env perl the user's favorite perl version is run. – ott-- Feb 03 '15 at 20:33
  • @ott not really - in your example the interpreter is /usr/bin/env with its first argument being perl. The work interpreter is a bit ambiguous in this case. – peterph Feb 04 '15 at 13:40