Starting of bash script

2019-08-07 07:30发布

问题:

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 ?

回答1:

If you call the script with an explicit interpreter, like

 bash foo.sh
 /bin/bash foo.sh
 dash foo.sh
 sh foo.sh

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:

 chmod a+x foo.sh
 ./foo.sh

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:

 #!/usr/bin/env python 

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 and bash.



回答2:

check out shebang!.

http://en.wikipedia.org/wiki/Shebang_%28Unix%29



回答3:

Try the following (shall I precise that this is not harmful):

  • create a new file containing:

    #!/bin/rm
    whatever
    
  • set executable bit with chmod +x the_file
  • run with ./the_file
  • see that your file disappeared magically.

So, as Kent suggests, she-bang in an executable file tells the path to another executable file that will be used as an interpreter.



回答4:

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.



回答5:

To invokes the Bourne shell or a compatible shell in your script.

Look: Shebang