Run a command under a different environment

Today we have a simple tip of the shell. Are there applications or scripts that you use that require different environment variables, such as a different PATH or EDITOR? Then meet the env command. env allows you to run a program in a restricted environment with custom variables or so that no "dirty" variables are left around.

Rather than explain how to use it, let's just jump in to some examples:

Let's say you have some custom Python modules that you installed to your home folder. To start up Python with these custom modules, you would use something like this:
$ env PYTHONPATH="/home/user/python" python
>>> import sys; sys.path
['', '/home/user/python', '/usr/lib/python2.5', ... ]

Maybe you want to edit your crontab with vim today:
env EDITOR=vim crontab -e

Perhaps you want to start a shell without any environment variables present at all:
env - sh

Another use of the env command is finding out what variables are currently set on your system.
$ env
LESSOPEN=| /usr/bin/lesspipe %s
LESSCLOSE=/usr/bin/lesspipe %s %s

Many shells also support omitting env completely if you just want to set variables and don't care about clearing the environment.
$ PYTHONPATH="/home/user/python" python

There you have it. The next time you see "this program depends on the following environment variables" on a man page, you'll know what to do.

Avatar for jacob Jacob Peddicord -

Jacob is a web developer, student, and programmer from Ohio. He is a staff member at the Ubuntu Forums and is most likely a fanboy of the distribution. He loves to write in code and words, play video games, and rant about topics most would have abandoned long ago. Jacob uses GNOME and is never seen running stable software, much to the demise of his laptop.

Home » Articles »

Discussion: Run a command under a different environment

Home » Articles » Run a command under a different environment