[GTALUG] Bash does-directory-exist question

Giles Orr gilesorr at gmail.com
Fri Jul 10 09:38:48 EDT 2020


I have a strange Bash question for you.  It's an edge case, but I've
run into it just often enough that I'd like to know how to deal with
it.

How do you determine if the directory you're in has been deleted?

I've done this to myself: 'cd' to a directory in one terminal, then
'rm -r' that same directory in another terminal.  It becomes very
confusing when you try to do something in the first terminal: 'touch
test.txt' responds with "touch: cannot touch 'test.txt': No such file
or directory".  Which is exceptionally hard to decipher because of
course it doesn't exist, I was trying to create it!

The worst case I've seen is 'git', and this is what's brought me back
to this puzzle. If you're in a directory and you 'git rm' the last
file in the directory, 'git' will helpfully delete the directory as
well.  Never mind that you're still in the directory, and are now in
the very confusing position of being in a non-existent directory.

One of my hobbies is tinkering with Bash Prompts.  It's fairly easy to
use 'test/[' to determine if a directory is writable with 'if [ -w .]
...' and then change the colour of the prompt based on the response.
This gives immediate visual feedback on the write-status of the
current directory.  But test's '-w' and '-d' both claim that you're
still in a valid directory under the above circumstances.  Does anyone
know of a simple way to find out if the directory you're currently in
actually exists?

I may have found my own answer: 'stat .' returns (in part) "Links: 0"
which would seem to indicate a non-existent node.  Is that a
definitive answer?  (I don't use 'stat' much.)  I'm also interested to
see if anyone else has a simpler or more "Bash" answer.

Thanks.

-- 
Giles
https://www.gilesorr.com/
gilesorr at gmail.com


More information about the talk mailing list