Bash – How to create a clean shell environment for temporary use

bashenvironment-variablesprofile

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.

Best Answer

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.