Comment effects (#) of lines before and / or after comment line #! / Bin / sh

Example 1

#!/bin/sh # purpose: print out current directory name and contents pwd ls 

Example 2

 # purpose: print out current directory name and contents #!/bin/sh pwd ls 

What is the difference - if I make the first line a comment ( # ) and #!/bin/sh second line, what will happen?

What does #!/bin/sh mean?

+6
source share
2 answers

Typically, a shell script is started by your default shell defined in the / etc / passwd file. But you can explicitly define a program that can run your script.

Unices uses a generic method to determine which program should run for a particular script (man execve (2) ). If the script has the correct execution rights, and in the script the first line begins with the characters #! , it will be launched by the program defined subsequently.

For example, if the first line is #!/usr/bin/awk -f , the rest of the file will be passed to awk (so it should use awk syntax). Or, if the Makefile starts with #!/usr/bin/make -f , the rest of the file will be passed to make . You can run the script as a regular program, and the script can be written in awk or make syntax (or any other).

If execve does not find #! as the first two characters of the file, it will be considered as a regular script file, and it will work as is.

So using #! You can define the script language, and you do not need to know which shell is being used by another user using your script. On any other line #! your default shell will be interpreted, which is usually a comment line.

+2
source

what is the difference between the 1st and 2nd shell scripts.?

No difference in output. But the time to complete both will be slightly different, as the interpreter reads the lines one by one.

if I give a comment (#) in the 1st line after #! / bin / sh in the 2nd line, so what happens?

Any line starting with (#), except for shebang (#!), Is treated as a comment in a shell script.

what does #! / bin / sh mean?

Its path (here / bin / sh) to the interpreter used after shebang (#!). Shell will try to use the interpreter language mentioned after shebang to execute the script.

+1
source

Source: https://habr.com/ru/post/944847/


All Articles