I want to run a program in an empty environment (i.e. with no envariables set). How to do this in bash?
Bash Environment – How to Run a Program in a Clean Environment in Bash
bashenvironment-variables
Related Solutions
To load environment variables you've put into a file, you can use the source
command. e.g.
See current path:
> echo $PATH
/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin
File with custom environment settings..
> cat exports
export PATH="/home/me/bfin2012:$PATH"
export ...
Load custom environment
> source exports
Confirm changes.
> env | grep '^PATH'
PATH=/home/me/bin2012:/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin
Given the file you show, you should be able to do:
(set -f ; IFS='
' ; env - $(cat /path/to/file) /path/to/your/program
)
If it doesn't work then it is only because you need to format your environment file first. Here's an example:
(set -f ; IFS='
' ; env - $(cat) printenv
) <<\ENV
variable1=value1
variable2=value2
variable3=value3 an$d s'om\e m"ore
ENV
###OUTPUT###
variable1=value1
variable2=value2
variable3=value3 an$d s'om\e m"ore
I at first thought you could do it through the shell - but it will probably set some of its own environment before calling your program. But I can at least demonstrate that the arguments are assigned correctly:
(set -f; IFS='
' ; env - $(cat) sh -c 'echo "$variable3"'
) <<\ENV
variable1=value1
variable2=value2
variable3=value3 an$d s'om\e m"ore
ENV
###OUTPUT###
value3 an$d s'om\e m"ore
Still, if you would prefer to source it, here's how you can using the shell:
(echo '$1'; cat; echo '$2') <<\ENV |\
env - sh -s -- 'set -a' printenv
variable1=value1
variable2=value2
variable3='value3 an$d s'\''om\e m"ore'
ENV
###OUTPUT###
PWD=/home/mikeserv/test
SHLVL=1
variable1=value1
variable2=value2
variable3=value3 an$d s'om\e m"ore
_=/usr/bin/printenv
Notice that I removed the $IFS
stuff - that's not necessary this way - but I did have to get specific about the quotes in the file. Here I'm essentially .dot
sourcing stdin
- reading the |pipe
as input - but you can use any file. I use set -a
before reading the input file to set the --allexport
option.
That is a result of using bash
's sh
- it adds $PWD
, $SHLVL
and $_
. With dash
it is a little better. And dash
doesn't add a bunch of exports either, so you can specify the -a
parameter on the command line:
(cat; echo '$1') <<\ENV |\
env - dash -sa -- printenv
variable1=value1
variable2=value2
variable3='value3 an$d s'\''om\e m"ore'
ENV
variable1=value1
variable2=value2
variable3=value3 an$d s'om\e m"ore
PWD=/home/mikeserv/test
Only $PWD
comes through.
Best Answer
You can do this with
env
: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:
i.e. wipe the environment and then print it. The output will be blank.