I think this is overthinking the problem.
cd . may not be something that one would manually run in the usual course of things, but it definitely is something that can come up in programmatic execution (think of any situation where you might
cd to the directory containing a file, whose path is supplied by the user). Therefore, it doesn’t have to have some specific use: as long as it fulfills the usual semantics of
cd <some-path>, it is useful.
The path of the directory could have changed since the last command was executed, and without
cd . the bash and ksh93 shells will rely on the logical working directory described in the post linked in the question, so calling
cd . which makes the shell issue the
getcwd() syscall will ensure your current path is still valid.
Steps to reproduce in bash:
- In a terminal tab issue
mkdir ./dir_no_1; cd ./dir_no_1
- In a different terminal tab issue
mv dir_no_1 dir_no_2
- In the first terminal tab issue
pwd. Notice that the directory has been externally renamed; the shell’s environment has not been updated.
cd .; pwd; echo $PWD. Notice the value has been updated.
ksh93, however, does not update the environment information, so
cd . in ksh93 may in fact be useless. In
/bin/dash on Ubuntu and other Debian-based systems,
cd . returns
dash: 3: cd: can't cd to . error, however
cd -P . works (unlike in ksh93).
Another use case of
cd . would be when the directory you currently are in has been deleted and then made again. Consider trying the following –
- Create a directory
cd tempand then do an
- Open another terminal and delete and then recreate that directory
- Back from the first terminal, try doing an ls. This would result in an error –
ls: cannot open directory .: Stale file handle
cd .and then doing an ls works fine