Open a terminal in the current working directory

I use i3, which is a great tiling window manager. Everything is keyboard driven, and the default keybindings are vim-like, so its great. I spend a lot of time in the terminal, so its very easy to open a new terminal, and the terminal I'm already using will automatically be resized to fit both on the screen. However, the issue I had early on was that opening a terminal with the keybinding (alt-enter by default, alt-t on my machines) would open a terminal in the home directory. If I am working on code buried 5 levels below my home directory and I want to open a new terminal in the same directory so I can run my unit tests, this is a pain in the ass.

There are bookmarking utilities that help, bashmarks for example, but I wanted something that would be automatic. I finally stumbled onto a blog post (I don't even remember where) that shows how to get window properties using the xprop command. So, I created a script named terminal-here that will first cd to the working directory of the currently focused window, and then launch a terminal. This has the effect of opening a terminal in the same working directory as the terminal I am currently working in. Here is the script.

#! /bin/bash

ID=$(xprop -root | gawk '/_NET_ACTIVE_WINDOW\(WINDOW\)/{print $NF}')
PID=$(xprop -id $ID | gawk '/_NET_WM_PID\(CARDINAL\)/{print $NF}')
SH=$(basename $SHELL)
ZPID=$(pstree -lpA $PID | sed -n "/$SH/ s/.*$SH(\([0-9]\+\)).*/\1/p")

if [[ -n $ZPID ]]
then
  CWD=$(readlink /proc/$ZPID/cwd)
fi


TERMINALS="kitty $HOME/.local/kitty.app/bin/kitty urxvt termite terminology rxvt xterm"
for T in $TERMINALS
do
  if which $T
  then
    TERMINAL=$T
    break
  fi
done

if [[ -n $CWD ]]
then
  cd $CWD
fi

echo $TERMINAL
$TERMINAL "${@}"

To use the script, you just need to put it in a directory listed in your PATH variable, and run terminal-here when you want a terminal. I changed my i3 keybindings to call this script instead of i3-sensible-terminal. You can see that I have a list of terminals I use, and the script looks for one that works. You can set TERMINALS to a list of your favorite terminals, or just set TERMINAL to the one you use directly (you could even set it to i3-sensible-terminal).

links

social