Weird behavior while moving a directory - Servers Administration, Networking, & Virtualization

Users browsing this thread: 1 Guest(s)
Long time nixers
Nice question, I love little riddles like this. :-)

So, the point is, Bash itself is holding a reference to the current working directory -- but that reference is a string. Let's have a look at Bash's source code.

"builtins/cd.def": Both "cd" and "pwd" are defined here. IIUC, the function pwd_builtin() is what's being executed when you type "pwd". It uses a shortcut:

#define tcwd the_current_working_directory
  directory = tcwd ? (verbatim_pwd ? sh_physpath (tcwd, 0) : tcwd)
           : get_working_directory ("pwd");

It uses the value of "the_current_working_directory", if set. Aha. Below that, there's this piece of code:

/* Try again using getcwd() if canonicalization fails (for instance, if
     the file system has changed state underneath bash). */
  if ((tcwd && directory == 0) ||
      (posixly_correct && same_file (".", tcwd, (struct stat *)0, (struct stat *)0) == 0))
      if (directory && directory != tcwd)
        free (directory);
      directory = resetpwd ("pwd");

So, Bash tries to detect whether its current value of "tcwd" is still valid. It uses same_file() to do that, defined in "general.c". This checks whether "." and "tcwd" point to the same inode on the same device. Yes, of course they do. But that doesn't mean that the cwd's directory name is still valid!

-- edit: No, wait, I'm confused. "tcwd" is the old directory name, it's invalid. But strace shows that there are no calls to stat() anyway, so I'd assume the code doesn't even execute the call to same_file(). Probably because posixly_correct is not set.

Yeah, if I start a Bash with "POSIXLY_CORRECT=1 bash", then "pwd" shows the new directory name (and I see calls to stat() in strace).

This is indeed weird. Why not just call the syscall getcwd() and be done with it? Why the hazzle with holding a string (!) reference to the cwd? I suspect this is for historical reasons ...

Messages In This Thread
RE: Weird behavior while moving a directory - by movq - 30-09-2016, 09:59 AM