Can I spawn a new terminal that is a clone of the current terminal?

23,768

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.

Share:
23,768

Related videos on Youtube

John Berryman
Author by

John Berryman

Updated on September 17, 2022

Comments

  • John Berryman
    John Berryman over 1 year

    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?

  • John Berryman
    John Berryman over 13 years
    Wow... cool explanation that lead to some insights that I have had before.
  • John Berryman
    John Berryman over 13 years
    I modded you script to take an argument and place the put and get the environment to a file named by the argument... now I can have several environments! :D
  • John Berryman
    John Berryman over 13 years
    Question: what does "." do in getstate?
  • Jander
    Jander over 13 years
    The "." says, "Run the contents of this file using the current shell, as if they were typed at the command line". Without the ".", a new copy of bash would run the commands in the file and then exit, and the current shell's environment wouldn't change.