How can I open a new terminal in the same directory of the last used one from a window manager keybind?

I'm currently using this version of #1 solution

# save path on cd
function cd {
    builtin cd $@
    pwd > ~/.last_dir
}

# restore last saved path
if [ -f ~/.last_dir ]
    then cd `cat ~/.last_dir`
fi

inside my .zshrc


This is actually pretty trivial; if you run urxvt from within your existing urxvt window, the new window will be in the same directory. I have dup aliased to urxvt & for this reason. If you want it bound to a hotkey, you can use bash's bind command. For example, to bind it to F1:

$ bind '"\e[11~": "urxvt &\n"'

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.