Change directory in Terminal if working folder moved to Trash (in interactive shell)?

So occasionally I will be working in zsh, in an interactive shell, and will shift to the Finder (or Path Finder) and while there will throw the folder, that is the current working directory in the Terminal, into the Trash. I'll then later go back to the shell for something else, and find that the shell is still in the now-deleted folder.

Is there a way where zsh can figure out that, if the folder's parent has changed to become ".Trash", it should, say, change its directory (in my case, ideally to the desktop folder)? But that it should only do this in an interactive shell, as opposed to the middle of a shell script or other app?

I can Google and implement but haven't been able to find the right terms, and am more sort of what I call a splicer or a kludger than any sort of real programmer. Hoping someone's thought along these lines before.


Solution 1:

No, there's no way for Zsh to automatically notice that while you are not actively using it.

But what does it matter? You can just type cd to go back to your home folder.

Update

All right, here's a real solution that I've tested and it works. Thanks to @nohillside for the encouragement!

autohome() {
  # If the present working dir doesn't exist...
  if [[ ! -d $PWD ]]; then
    # Go back to ~
    cd $HOME

    # If the line editor is active, redraw the prompt.
    zle && zle .reset-prompt
  fi
}

# This will call the function above as soon as you start typing.
autoload -Uz add-zle-hook-widget
add-zle-hook-widget line-pre-redraw autohome