2

Is there a way to cd out of a directory which has just been deleted (go up one level into the upper folder which still exists?

It often happens to me that I have a console opened for a folder, and then I delete the folder with my temporary test data and create another one.

However, both cd .. and cd $(pwd)/.. only get me to the trash bin, and not to the upper directory when I try to leave the deleted folder.

So, current situation is:

$ mkdir -p /home/me/test/p1
$ cd /home/me/test/p1

now I delete the folder p1

$ cd ..
me:~/.local/share/Trash/files$ ...

I'm now searching for a way to get into /home/me/test/ and not into the Trash bin. Is there such a command?

  • Note: you should use $PWD and not $(pwd). Bash keeps track of names of directories in PWD. Instead the command pwd gives the current working directory (so it moves with directory moving or symlinks). – Giacomo Catenazzi Mar 27 '16 at 16:25
0

PWD variable hold current path definition.

to go up one level

cd $(dirname $PWD)

will expand to

cd $(dirname /home/me/foo/bar/baz/deleteddirectory)

who expand to

cd /home/me/foo/bar/baz/

this supposed you delete only one level of dir.

  • For me, basename /home/me/foo/bar/baz/deleteddirectory expands to deleteddirectory and not to /home/me/foo/bar/baz – Florian Bach Mar 27 '16 at 9:45
  • I found dirname which seems to do what I want to - cd $(dirname $PWD) gets me out of the deleted folder. – Florian Bach Mar 27 '16 at 9:47
0

The shell stores the path to the current working directory in the variable PWD. Unless configured otherwise, that's the path as specified to the shell, even if the directory has been moved or if symbolic links are involved. So you can use this to change to the apparent parent of the directory, even if the actual location of the directory is different. E.g. cd /foo/bar sets PWD to /foo/bar even if bar is a symbolic link (cd -P makes the shell resolve the symbolic link instead) and PWD remains set even if the directory is then moved or deleted.

Thus you can change to the apparent parent directory by taking PWD and stripping off the part after the last slash:

cd ${PWD%/*}

If there are whitespace or wildcards in the path to the directory then you need quotes:

cd "${PWD%/*}"

In zsh this can be abbreviated to

cd $PWD:h

You can also use the longer but perhaps more memorable

cd "$(dirname "$PWD")"

(double quotes not needed if no whitespace or wildcards are in the directory name).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.