You are currently browsing the archives for the screen tag.

Using Screen to emulate tabs

Screen1 is a wonderful tool which allows to use just one terminal emulator to launch multiple interactive shells.

The idea I had is the following : using screen and xterm together, it is possible to have a tabbed terminal emulator (hype, but so useful), and moreover, one can simply detach the session and reattach it later. Of course, there are a few annoying things:

  • having to call screen when opening a new xterm
  • having to exit screen and then hafing to exit xterm (except if one does a pow detach, but you don't always think about it
  • the key bindings are logical, but they are not intuitive (there exist simpler bindings that C-a c, C-a p and C-a n to, respectively, spawn a shell, go to the previous one, go to the next one…)

There is a solution to each of the points I've stated. First, to change the key bindings, we have to edit the .screenrc. In order to find the keycodes, a $ cat followed by the keys you want will do great. Here is a extract of my .screenrc

# ctrl-left : previous
bindkey ^[[1;5D prev
# ctrl-right : next
bindkey ^[[1;5C next
# ctrl-down : spawn a new shell
bindkey ^[[1;5B screen

Once this is done, it's just a matter of modifying the .bashrc:

# an alias to launch an xterm without screen, if needed
alias xtermds="DISABLE_SCREEN='1' xterm"

if [[ $TERM == 'xterm' ]]; then
  # not in an xterm, do nothing
  if [[ $DISABLE_SCREEN != 1 ]]; then
    # if $DISABLE_SCREEN = 1, do nothing
    if [[ `screen -list | grep "Detached" | wc | awk ' { print $1}'` == 0 ]]; then
      # if there is no detached screen, create a new one
      screen
    else
      if [[ `screen -list | grep "Detached" | wc | awk ' { print $1}'` == 1 ]]; then
        # if there is a single detached screen, reattach it
        screen -r;
      else
        # if there are several, reattach anyone of them
        screen -R $(screen -list | grep "Detached" | head -n1 | sed "s/\..*//g" | awk '{ print $1 }');
      fi;
    fi;
    # wait until screen returns
    wait
    # and close the xterm
    exit;
  fi;
fi;

Now we have a tabbed xterm, which calls screen by itself, quits when we exit screen and has usable key bindings. And yet it is still possible to have screenless xterms (useful to ssh somewhere and have a distant screen).

  1. GNU screen []