Thursday, May 20, 2010

» GNU Screen: open new window with same working directory

I do this many, many times every single day, and I finally found how to implement it: a shell function to open a new window in screen which is automatically in the same directory as where you call that function. Here is the bash code to add to your ~/.bashrc: function dupscreen { screen bash -c "cd \"$PWD\" && exec $SHELL --login" } alias ,d=dupscreen When I'm in screen and I need another shell in the same directory (e.g. because I'm opening a spec file in vim and need another shell to test the build of the RPM package with osc), I then just type ,d ! Yes, I know, I'm lazy. For the record, here is the nitty gritty on how this works:
  • when you run /usr/bin/screen while already being in screen, it doesn't start a new screen process -- instead, it performs the requested operation (in this case, launching a process (bash) inside screen) in the same screen instance, which is pretty much the same as.. Firefox is doing ;D); note that screen notices that you are already inside a screen session because the environment variable STY is set and points to the name of the screen session you're in
  • bash can be passed a command to execute (instead of going into an interactive shell) using the -c switch; in this case, we ask bash to run cd "$PWD" && exec $SHELL --login and exit
  • the internal bash variable PWD contains the name of the current directory
  • the environment variable SHELL is set by login and contains the login shell that is configured for your user
So basically, the function dupscreen is telling screen to run bash inside itself, and that bash changes into the current directory (i.e. the directory you're in when you call that function) and then executes $SHELL (which is most probably also bash) from there. The ,d shell alias is for extra lazyness :)

Labels: ,

3 Comments:

Blogger Dustin Lacewell said...

Hey thanks, this is just what I needed and you posted this only 6 days before I thought to figure it out.

02:44  
Anonymous Anonymous said...

Ah, thanks, been wondering so long how to get screen not to exit after changing to my favorite directories...

10:43  
Blogger skoneka said...

Hi, your article inspired me to improve the method. >>Here I described the way to duplicate window's working directory when running any program (not only shell). It is more complicated, but worth the effort.

00:45  

Post a Comment

<< Home