2

Often, I'm leaving the terminal and the next day run it again. Then I want to be able to quickly go back to the last working directory.

I would like to do this using cd - as usual. But $OLDPWD is not kept between terminal sessions.

So I added an alias for exit to write pwd to a file and read it on the next start.

alias exit='pwd > ~/.lwd && exit;'
test -f ~/.lwd && export OLDPWD=`head -1 ~/.lwd`

That works perfectly for exit.

How can I create the same alias (or make a trap) for Ctrl+D ?

pLumo
  • 26,947
  • alias is for command, ctrl-d isn't a command but a keyboard combo – Anwar May 11 '17 at 06:46
  • Sure I know. But has the same effect in this case: Exit the terminal. And as it is faster I tend to use it more often. – pLumo May 11 '17 at 06:48
  • 2
    Your main object is to open the terminal on the last cded directory, right? Then this might be of some help – Anwar May 11 '17 at 06:52

2 Answers2

4

Use trap to add a handler for EXIT:

trap 'pwd > ~/.lwd' EXIT

This should handle both the exit command and CtrlD. The rest, you can do as with the alias.

muru
  • 197,895
  • 55
  • 485
  • 740
4

Thanks to Anwar to lead me in the right direction. This post from the Unix & Linux Stack Exchange helped me.

I created a file ~/.bash_logout with following content:

echo "$PWD" > ~/.lwd

In ~/.bashrc I added:

test -f ~/.lwd && export OLDPWD=`head -1 ~/.lwd`

This works for exit and CtrlD for gnome-terminal and for ssh connections.

pLumo
  • 26,947