Shell – spawn a new terminal that is a clone of the current terminal

environment-variablesshellterminal

So let's say I'm developing code in directory /asdf/qwer/dfgh/wert/asdf/qwer and I've added about three more directories like that to my path and I have a bunch of arcane environment variables set. Then I realize that I really need another terminal open and set up in just this same way (although this need is not reoccurring so that I would just alter my .bashrc). Is there any command to open a new terminal window that is an exact clone of this one?

Best Answer

Cloning the path is easy if you can run your terminal program from the command line. Assuming you're using xterm, just run xterm & from the prompt of the terminal you want to clone. The new xterm will start in the same directory, unless you have it configured to start as a login shell. Any exported environment variables will also carry over, but un-exported variables will not.

A quick and dirty way to clone the whole environment (including un-exported variables) is as follows:

# from the old shell:
set >~/environment.tmp

# from the new shell:
. ~/environment.tmp
rm ~/environment.tmp

If you've set any custom shell options, you'll have to reapply those as well.

You could wrap this whole process into an easily-runnable script. Have the script save the environment to a known file, then run xterm. Have your .bashrc check for that file, and source it and delete it if found.


Alternately, if you don't want to start one terminal from another, or just want more control, you could use a pair of functions that you define in .bashrc:

putstate () {
    declare +x >~/environment.tmp
    declare -x >>~/environment.tmp
    echo cd "$PWD" >>~/environment.tmp
}

getstate () {
    . ~/environment.tmp
}

EDIT: Changed putstate so that it copies the "exported" state of the shell variables, so as to match the other method. There are other things that could be copied over as well, such as shell options (see help set) -- so there is room for improvement in this script.

Related Question