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

user1187968 picture user1187968 · May 4, 2017 · Viewed 20.3k times · Source

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?

Answer

user513951 picture user513951 · May 4, 2017

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.