I am a frequent answerer on a Unix-focused popular Q&A site, and in many of my answers I provide examples using the bash
shell. However, each time I do this I have to manually go through the process of creating a clean environment to make sure that every step is accounted for and documented. How can I make this process more straightforward? I am ideally looking to type a single command and get a clean environment, and have all traces of that temporary environment removed after I am done.
Asked
Active
Viewed 2,563 times
15

Gilles 'SO- stop being evil'
- 829,060
-
related: How to run a program in a clean environment in bash? – miracle173 Nov 14 '12 at 05:11
2 Answers
10
I personally use the following bash
function to do this:
so() {
local tmpdir="$(mktemp -d)"
local tmprc="$(mktemp)"
cat > "$tmprc" << EOF
PS1='\\$ '
cd "$tmpdir"
EOF
env - HOME="$HOME" TERM="$TERM" bash --rcfile "$tmprc"
rm -rf "$tmpdir" "$tmprc"
}
Here is what it does, in order:
- Create a temporary directory (to use as our working directory in the clean environment);
- Create a temporary file (to use as our
bash
rc file); - In the rc file, add lines which:
- Set the
PS1
prompt to the prompt terminator followed by a space, which keeps it relevant in case we want to have a copy of our output on the Q&A site; - Change into the temporary directory we created.
- Set the
- Invoke a new instance of
bash
, which:- Initially has an empty environment except for
$HOME
and$TERM
(env - ...
); - Reads its rc file from the temporary file we created earlier (
--rcfile
).
- Initially has an empty environment except for
- Once bash has exited, remove the temporary files we created.
Obviously this is not totally foolproof, that is, you can still access other parts of your system. This does, however, provide a clean temporary environment which you can use for testing.

Chris Down
- 125,559
- 25
- 270
- 266
2
chroot
is one way, using a VM is another.
You could build up the chroot-environment on a LV, snapshot it, do your whatever and then revert to the snapshotted state.
Or - do the same with the VM (disk-snapshot) and revert all changes afterwards.
I usually do this with a freshly installed VM (using VirtualBox and kickstart or autoyast with PXE-boot).

Nils
- 18,492