“ls $PWD” and “ls .” get different files, strange caching perhaps

cwdlspwd

I have a strange problem on my Linux Mint machine (with solid-state drive if that matters). Somehow the machine (on multiple occasions) gets different files, and different content for the same file, if I do "ls $PWD" instead of "ls ." or just "ls". That means I can write the file into the present working directory and pick up something different copying it from another directory.

It's not $PWD set to the wrong thing, I can hand-type the directory name.

I've checked this pretty carefully, but it does come and go. That makes it hard to make and to test production scripts and code.

adam@RADIUM:/home/adam/cd2/adam_dev/rsim ==> ls .
ClearPrice.cme Makefile.win data gfiles rsim5.tmp src zlib
ClearPrice.src ReadMe.txt err include rsimdone.txt tools
Makefile build g2f out scripts vs2013
adam@RADIUM:/home/adam/cd2/adam_dev/rsim ==>
adam@RADIUM:/home/adam/cd2/adam_dev/rsim ==> echo $PWD
/home/adam/cd2/adam_dev/rsim
adam@RADIUM:/home/adam/cd2/adam_dev/rsim ==> ls $PWD
ClearPrice.cmd Makefile.win err include scripts vs2013
ClearPrice.src ReadMe.txt g2f out src zlib Makefile build
gfiles rsimdone.txt tools
adam@RADIUM:/home/adam/cd2/adam_dev/rsim ==>

Best Answer

This can happen if the current directory is renamed or moved while you're in it.

For example:

$ mkdir /tmp/X
$ cd /tmp/X
$ mkdir Y Z
$ cd Y
$ touch a b c d e f
$ mv ../Y ../A
$ mv ../Z ../Y
$ echo $PWD
/tmp/X/Y
$ ls
a  b  c  d  e  f
$ ls $PWD
$ 

You can spot the difference in looking at the inode number of the directory:

$ ls -ldi . $PWD
26871815 drwxr-xr-x 2 sweh sweh 4096 Jul 12 17:27 ./
26872035 drwxr-xr-x 2 sweh sweh 4096 Jul 12 17:27 /tmp/X/Y/

You can also detect this because /bin/pwd returns a different value

$ /bin/pwd
/tmp/X/A
$ echo $PWD
/tmp/X/Y

Basically, $PWD is just where the shell thinks you are, not necessarily where you really are :-)

Related Question