What is reason behind writing
#! /bin/bash
at the very starting of every bash script ?
I means, I know that it is kind of hack but I want to know how it exactly works ?
What is reason behind writing
#! /bin/bash
at the very starting of every bash script ?
I means, I know that it is kind of hack but I want to know how it exactly works ?
Try the following (shall I precise that this is not harmful):
create a new file containing:
chmod +x the_file
./the_file
So, as Kent suggests, she-bang in an executable file tells the path to another executable file that will be used as an interpreter.
To invokes the Bourne shell or a compatible shell in your script.
Look: Shebang
Unix doesn't use extensions (.sh, .bat, whatever) to identify file contents.
The "#!" notation (shebang) is a magic number used to tell the kernel how to execute a script by providing the path to its expected interpreter.
check out shebang!.
http://en.wikipedia.org/wiki/Shebang_%28Unix%29
If you call the script with an explicit interpreter, like
your choosen interpreter is used, no matter what the shebang says, which is just a comment.
If you make the script executable, and start it:
the kernel looks for the shebang and starts the program with the therein specified interpreter. Since the kernel doesn't know the PATH, the whole path has to be given, or
env
has to be used:to choose the local path for a program.
Since dash, bash, zsh and so on aren't fully compatible, you should call the program without a specific interpreter, because the author should have known what he does.
Maybe on your system
sh
is a link to/bin/bash
, but beware! The shell can introspect how it was called, and bash can act in a way, called POSIX mode, which is slightly different and only a subset of what it normally does.If you write scripts for installation or for servers, which might run on different platforms - think OsX, Linux, Solaris and so on, where different shells are available, you will try to restrict yourself to this subset, to gain a compatible, reusable result.
But on your private machine, you might prefer the more convenient shells like
zsh
andbash
.