0

When searching for .txt files that are in 2 different home directories only one shows up depending on the present working directory. Why is this?

/home/bob/1.txt 
/home/alice/dir1/2.txt

pwd /tmp
[root@host tmp]#find /home -name *.txt 
/home/bob/1.txt 
/home/alice/dir1/2.txt

pwd /home
[root@host bob]#find /home -name *.txt 
/home/bob/1.txt

Why does searching from within the bob directory only return the one file?

Demi
  • 47
  • 3
  • [ShellCheck](https://www.shellcheck.net) detects this and other common problems, and says to "[Quote the parameter to -name](https://github.com/koalaman/shellcheck/wiki/SC2061) so the shell won't interpret it." – that other guy Oct 28 '21 at 17:07

1 Answers1

2

Why does searching from within the bob directory only return the one file?

Because when the working directory is /home/bob, the *.txt in the find command is expanded by the shell (to 1.txt) and that is what is passed to find. That is, find /home -name 1.txt. That will find the file in /home/bob, but not the differently named one in /home/alice. It would find /home/alice/1.txt if such a file existed.

On the other hand, when the pattern does not match any file (relative to the working directory) it is passed on as a literal. At least by default -- you should be careful about this, because the pattern would instead be expanded to nothing if the nullglob shell option were in effect and the find command were executed from a location where the pattern didn't match any files.

If you want to ensure that shell pathname expansion is not applied to the pattern then quote it:

find /home -name '*.txt'

or

find /home -name \*.txt

or ....

John Bollinger
  • 160,171
  • 8
  • 81
  • 157