100 Useful Command-Line Utilities

by Oliver; 2014

49. env

There are 3 notable things about env. First, if you run it as standalone, it will print out all the variables and functions set in your environment:
$ env
Second, as discussed in An Introduction to the Command-Line (on Unix-like systems) - The Shebang, you can use env to avoid hard-wired paths in your shebang. Compare this:
#!/usr/bin/env python
to this:
#!/some/path/python
The script with the former shebang will conveniently be interpreted by whichever python is first in your PATH; the latter will be interpreted by /some/path/python.

And, third, as Wikipedia says, env can run a utility "in an altered environment without having to modify the currently existing environment." I never have occasion to use it this way but, since it was in the news recently, look at this example (stolen from here):
$ env 'COLOR=RED' bash -c 'echo "My favorite color is $COLOR"'
My favorite color is RED
$ echo $COLOR

The COLOR variable is only defined temporarily for the purposes of the env statement (when we echo it afterwards, it's empty). This construction sets us up to understand the bash shellshock bug, which Stack Exchange illustrates using env:
$ env x='() { :;}; echo vulnerable' bash -c "echo this is a test"
I unpack this statement in a blog post.

<PREV   NEXT>