Suppose I am editing some files. I have (say) a terminal open and a gui file manager.I am currently in /my/very/long/and/winding/directory/path in the terminal.In my gui, I delete /my/very/long/and/winding/directoryBack in the terminal, I try cd .. and I get an error, since the directory no longer exists.No big deal. I could type cd /my/very/long/and/winding to get back where I want to go. But if I'm too lazy to type that, is there a nice way to go back to the nearest directory that still exists?edit: cd ../../ is one solution, in this particular case. But I'm wondering if there is a more general answer, where I don't know how many steps back I need to take.
Retreat from deleted directory
command line
Assuming PWD is correct, one can back out in ZShell thusly.% cd ~/tmp% mkdir -p a/a/a/a/a/a/a/a/a/a/a% cd !$cd a/a/a/a/a/a/a/a/a/a/a% rm -rf ~/tmp/a% undir% pwd/Users/jmates/tmp% The custom undir function does the walk-back-out-the-path-chain loop:function undir {  local dir  dir=$PWD:h  while [[ $dir != / ]]; do    builtin cd -q $dir 2>/dev/null    if [[ $? -eq 0 ]]; then      dir=/    else      dir=$dir:h    fi  done}Note that you cannot rely on the pwd command, as that gives different results than the shell-maintained PWD variable:% mkdir -p a/a/a/a/a/a/a/a/a/a% cd !$cd a/a/a/a/a/a/a/a/a/a% rm -rf ~/tmp/a% pwd/Users/jmates/tmp/a/a/a/a/a/a/a/a/a/a% cd ..% pwd.% echo $PWD/Users/jmates/tmp/a/a/a/a/a/a/a/a/a% Shells that are not zsh will undoubtably require other solutions.