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 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.

share|improve this question
    

2 Answers 2

up vote 6 down vote accepted

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.
  • 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).
  • 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.

share|improve this answer
    
have you tried using script? –  h3rrmiller Nov 9 '12 at 16:12
    
@h3rrmiller - Yes, although I tend not to use it out of preference. –  Chris Down Nov 9 '12 at 16:28

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).

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.