Starting of bash script

2019-08-07 07:56发布

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 ?

5条回答
家丑人穷心不美
2楼-- · 2019-08-07 07:58

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.

查看更多
家丑人穷心不美
3楼-- · 2019-08-07 08:01

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

Look: Shebang

查看更多
SAY GOODBYE
4楼-- · 2019-08-07 08:02

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.

查看更多
Lonely孤独者°
6楼-- · 2019-08-07 08:15

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.

查看更多
登录 后发表回答