JohnJ
JohnJ

Reputation: 7066

tilde expansion does not work on certain directories

I found something really bizzare today - the tilde expansion does not seem to work on one of my directories.

So, I have a bunch of jpg files in a directory and I do this:

find . -maxdepth 3 -type f -name '*.jpg' | wc -l
>>> 10000

but when I do this:

find ~+ -maxdepth 3 -type f -name '*.jpg' | wc -l
>>> 0

WTF!!!??

I have not encountered this before and I was wondering what is it that I have stumbled on! I have other directories and the tilde expansion works fine in all of them :(

Upvotes: 1

Views: 58

Answers (1)

jhnc
jhnc

Reputation: 16908

This is an interaction between find and bash:

  • find normally doesn't follow symbolic links
  • bash does not canonicalise PWD
bash$ TOP=/tmp/foo
bash$ rm -rf "$TOP"
bash$ mkdir -p "$TOP"/a1/{x,y,z}
bash$ ln -s a1 "$TOP"/a2

bash$ (cd "$TOP"/a1; realpath ~+; echo $PWD ~+; find ~+;)
/tmp/foo/a1
/tmp/foo/a1 /tmp/foo/a1
/tmp/foo/a1
/tmp/foo/a1/z
/tmp/foo/a1/y
/tmp/foo/a1/x

bash$ (cd "$TOP"/a2; realpath ~+; echo $PWD ~+; find ~+;)
/tmp/foo/a1
/tmp/foo/a2 /tmp/foo/a2
/tmp/foo/a2

A fix is to use find's -H option, or append a /:

bash$ (cd "$TOP"/a2; realpath ~+; echo $PWD ~+; find -H ~+;)
/tmp/foo/a1
/tmp/foo/a2 /tmp/foo/a2
/tmp/foo/a2
/tmp/foo/a2/z
/tmp/foo/a2/y
/tmp/foo/a2/x

bash$ (cd "$TOP"/a2; realpath ~+; echo $PWD ~+; find ~+/;)
/tmp/foo/a1
/tmp/foo/a2 /tmp/foo/a2
/tmp/foo/a2/
/tmp/foo/a2/z
/tmp/foo/a2/y
/tmp/foo/a2/x

Upvotes: 2

Related Questions