How to run a program in a clean environment in bash?
You can do this with env
:
env -i your_command
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.
A "clean" bash
environment may be had with
$ env -i bash --noprofile --norc
The
env -i
command executes the command given to it on the command line without transferring any of the exported environment variables of the old shell environment to the environment of the executed program.The
--noprofile
option stopsbash
from reading the system-wide or personal shell initialization scripts that would otherwise be read for a login shell.The
--norc
option stopsbash
from reading the personal shell initialization scripts that would otherwise be read for an interactive shell.
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