Shell – Difference between find ~ and find *

filenamesfindshellwildcards

What is the difference between find * and find ~ for searching a file?
In terminal when my present working directory on root,then in terminal

root@devils-ey3:~# find * -print -quit
~

On same directory

root@devils-ey3:~# find ~ -print -quit
/root

But if I change the pwd then the output of find ~ -print -quit is same as before but the other is change.
What is the working purpose of * and ~ for find file ?

Best Answer

The basic format of find is

find WHERE WHAT

So, in find *, the * is taken as the WHERE. Now, * is a wildcard. It matches everything in the current directory (except, by default, files/directories starting with a .). The Windows equivalent is *.*. This means that * is expanded to all files and directories in your current directory before it is passed to find. To illustrate, consider this directory:

$ ls
file  file2

If we run set -x to enable debugging info and then run your find command, we see:

$ find * -print -quit
+ find file file2 -print -quit
file

As you can see above, the * is expanded to all files in the directory and what is actually run is

find file file2 -print -quit

Because of -quit, this prints the first file name of the ones you told it to look for and exits. In your case, you seem to have a file or directory called ~ so that is the one that is printed.

The tilde (~), however, also has a special meaning. It is a shortcut to your $HOME directory:

$ echo ~
/home/terdon

So, when you run find ~, as root, the ~ is expanded to /home/root and the command you run is actually:

# find ~ -print -quit
+ find /root -print -quit
/root

Again, you are telling find to search for files or directories in a specific location and exit after printing the first one. Since the first file or directory matching /root is itself, that's what is printed.

Related Question