Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do you need shebang in all bash scripts? [duplicate]

Tags:

Suppose you have a bash script B, that you are sourcing from another bash script A. B has a bunch of variable and function definitions. A is the main driver script. Do you need the #!/bin/bash line on top of both A and B? What happens if you do and if you don't?

like image 621
Raihan Avatar asked Sep 30 '11 19:09

Raihan


People also ask

Is shebang necessary for bash script?

Shebangs should never really be necessary on any platform. If a shell script lacks a shebang, the script will be interpreted by whatever shell binary was called to interpret it. This is usually the same shell binary as the shell from which you invoked the script.

Is #!/ Bin bash necessary?

#!/bin/bash Essentially it tells your terminal that when you run the script it should use bash to execute it. It can be vital since you may be using a different shell in your machine ( zsh , fish , sh , etc.), but you designed the script to work specifically with bash.

What is the purpose of the bash shebang?

called shebang and is used to tell the Linux OS which interpreter to use to parse the rest of the file. You will always see #!/bin/bash or #!/usr/bin/env bash as the first line when writing or reading bash scripts. Shebang starts with #! characters and the path to the bash or other interpreter of your choice.


2 Answers

The shebang is only mandatory for those scripts, which shall be executed by the operating system in the same way as binary executables. If you source in another script, then the shebang is ignored.

On the other hand. IF a script is supposed to be sourced, then it is convention to NOT put any shebang at the start.

like image 179
A.H. Avatar answered Oct 01 '22 20:10

A.H.


The shebang is used if you run the script directly as an executable file (for example with the command ./script.sh). In this case it tells the operating system which executable to run.

It's not required and has no effect if you for example write bash ./script.sh or source the script.

like image 43
Mark Byers Avatar answered Oct 01 '22 19:10

Mark Byers