How does /usr/bin/env work in a Linux shebang line?

LinuxEnvironment VariablesShebang

Linux Problem Overview


I know shebang line like this:

#!/bin/sh

but I found out I can also use shebang line like this:

#!/usr/bin/env python3

This confuses me, can someone explain to me how Linux will process this one?

Linux Solutions


Solution 1 - Linux

env is the name of a Unix program. If you read the manual (man env) you can see that one way to use it is env COMMAND, where in your case, COMMAND is python3.

According to the manual, this will

> Set each NAME to VALUE in the environment and run COMMAND.

Running env alone will show you what NAMEs and VALUEs are set:

$ env
TERM=xterm-256color
SHELL=/bin/bash
PATH=/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin

Therefore, /usr/bin/env python3 is an instruction to set the PATH (as well as all the other NAME+VALUE pairs), and then run python3, using the first directory in the PATH that contains the python3 executable.

Solution 2 - Linux

Newer *nix versions will resolve this the same way as the command which works.

It looks in all directories which are set in the environmental variable $PATH, whereever it is set (global, in your .bashrc or other logon script or by hand), one by one and returns the first match.

Important is, that some linux versions create alias files (aka symlinks), e.g. debian.

Another note: the bash command alias overrides this behavior as it is performed first.

Solution 3 - Linux

Essentially like

tail -n +1 yourfile | /usr/bin/env python

Solution 4 - Linux

#!/bin/sh

is only the path of the interpreter binary, whereas

#!/usr/bin/env python3

has path of the interpreter passing python3 as optional argument to the #!/usr/bin/env interpreter

Please refer wiki for more info.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1187968View Question on Stackoverflow
Solution 1 - Linuxuser513951View Answer on Stackoverflow
Solution 2 - LinuxMarcel NolteView Answer on Stackoverflow
Solution 3 - LinuxHagen von EitzenView Answer on Stackoverflow
Solution 4 - LinuxBharathiView Answer on Stackoverflow