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?
Stack Exchange network consists of 181 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.Visit Stack Exchange
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.Sign up to join this community
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.
#!/usr/bin/env bashmight be better for portability
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.
#!/usr/bin/env perlthe user's favorite perl version is run.
/usr/bin/envwith its first argument being
perl. The work interpreter is a bit ambiguous in this case.