Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I want to run a program in an empty environment (i.e. with no envariables set). How to do this in bash?

share|improve this question
    
Possibly related: How to get a clean environment in a ksh shell –  rahmu Sep 25 '12 at 9:14

3 Answers 3

up vote 24 down vote accepted

You can do this with env:

env -i your_program

Contrary to comments below, this does completely clear out the environment, but it does not prevent your_command setting new variables. In particular, running a shell will cause the /etc/profile to run, and the shell may have some built in settings also.

You can check this with:

env -i env

I.e. wipe the environment and then print it. The output will be blank.

share|improve this answer
2  
It doesn't completely clear out the environment: echo 'echo $PATH' > test.sh && chmod u+x test.sh && env -i test.sh prints /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin. –  l0b0 Sep 24 '12 at 14:14
1  
However, it seems this is the closest you can get - It seems like variables like PATH, PWD and SHLVL are set automatically by Bash. +1. –  l0b0 Sep 24 '12 at 14:31
1  
@I0b0: See my edit. –  ams Sep 24 '12 at 14:37

env -i -- somecommand runs a command in an empty environment, as ams has already mentioned.

A lot of programs rely on some important environment variables, so you may want to retain them:

env -i HOME="$HOME" LC_CTYPE="${LC_ALL:-${LC_CTYPE:-$LANG}}" PATH="$PATH" USER="$USER" -- somecommand

Alternatively, you could log in into a small login-time environment.

ssh localhost somecommand
share|improve this answer
    
Works when running the command on cmdline. How do I put this in shebang?, doesn't seem to work! –  balki Nov 4 '13 at 17:16

To answer balki's comment (and answering my own question in the process :-):

% echo Environment in calling shell: vars: $(env |wc -l); echo; ./du; echo; cat du
Environment in calling shell: vars: 43

==> This is the environment: vars: 5
PATH="$PATH"
PWD=/Users/nick
SHLVL=1
SOMETHING_TO_KEEP="$USER"
_=/usr/bin/env
==> The end.

#!/usr/bin/env -i SOMETHING_TO_KEEP="$USER" PATH="$PATH" /bin/sh

echo "==> This is the environment: vars:" $(/usr/bin/env | /usr/bin/wc -l)
/usr/bin/env
echo "==> The end."
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.