Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linux shell: test if current directory has been deleted in case of it's re creation

I know this is not a usual thing to ask here, but may be someone already discovered a trick to test that.

I am using Linux Mint bash terminal and time to time the current directory becomes recreated because of outside actions. After the current directory is recreated outside, all commands like echo blabla > blabla fails because terminal holds the current directory handle open and user can not create files in a removed directory holded by opened handle which one became removed outside.

I know cd . could restore the handle of the current directory back to created one.

Is there a way to test the current directory handle holded by a terminal on a deleted state before call to cd .?

like image 905
Andry Avatar asked Sep 16 '25 02:09

Andry


1 Answers

Due to race conditions, testing for this condition is a bad idea.

Nevertheless because it's hard to trap, I give you the following:

checkcd()
{
    CINODE=$(ls -id . | cut -d ' ' -f 1)
    PINODE=$(ls -id `pwd` | cut -d ' ' -f 1)
    if [ $? -gt 0 ]
    then
           echo "Current directory is gone"
    elif [ $CINODE -ne $PINODE ]
    then
           echo "Current directory has been deleted and recreated; do cd `pwd` to fix"
    else
           echo "Current directory is ok"
    end if
}

There, now it's a function you can put into .bashrc and invoke as checkcd.

If you need to know how to use .bashrc here's your answer: https://unix.stackexchange.com/questions/129143/what-is-the-purpose-of-bashrc-and-how-does-it-work

like image 104
Joshua Avatar answered Sep 18 '25 18:09

Joshua