Bash – How to open a new terminal in the same directory of the last used one from a window manager keybind

bashcd-commandrxvtterminal

I'm using a tiling window manager and I switched from gnome-terminal with multiple tabs to multiple urxvt instances managed by the window manager. One of the features I miss is the ability to open a new terminal that defaults to the working directory of the last one.

In short: I need a way to open a new urxvt (bash) that defaults to $PWD of the last used one.

The only solution that comes to my mind is to save the current path on every cd with something like this:

echo $PWD > ~/.last_dir

and restore the path on the new terminal in this way:

cd `cat ~/.last_dir`

I can source the second command in .bashrc but I don't know how to execute the first one on every directory change 🙂

Any simpler solution that does not involve screen or tmux usage is welcome.

Best Answer

I see three solutions using .last_dir. You can place the echo $PWD > ~/.last_dir either:

  1. In a special function that would be a wrapper for cd:

    function cd_
    {
      [[ -d "$@" ]] || return 1
      echo "$@" > ~/.last_dir
      cd "$@"
    }
    

    Place this in your ~/.bashrc and then use cd_ instead of cd every time you want your new working directory to be stored.

  2. In your $PROMPT_COMMAND (not recommended):

    PROMPT_COMMAND="$PROMPT_COMMAND; pwd > ~/.last_dir"
    

    You can test this directly from the terminal or place it in ~/.bashrc. This solution, however, triggers a disk write each time the prompt appears, which might cause trouble - but on the other hand, .last_dir would contain the current directory no matter how you got there.

  3. In a custom perl extension script for rxvt. I've never created one myself, but you can find quite a few examples on the web.

Related Question