find, and Names With Spaces

What this is. find walks a directory tree and reports everything matching a description.

`

find . -name "*.js"

`

Read it as: starting here, find everything whose name matches *.js. The first argument is where to start, and everything after describes what you want.

-name pattern matches the filename.

-type f restricts to files, -type d to directories.

✦ Quote the pattern, always

Write find . -name "*.js" with quotes rather than find . -name *.js without them. Without quotes the shell expands the wildcard first, against the current directory, and hands find a single already-resolved filename. It then searches for exactly that one name and you get a confusing partial answer. The quotes stop the shell touching it, so find receives the pattern itself and applies it at every level of the tree.

SANKOFA SANDBOX
learner:~$

Try the quoted and unquoted forms back to back and compare.

Try it → From your home directory run `find . -name "*.js"` and then `find . -name *.js`. The first walks the whole tree. The second is a different question entirely, because the shell already answered part of it.

Names with spaces. A space separates arguments, so a file called my notes.txt looks like two arguments. Two ways round it:

cat "my notes.txt" quotes the whole name.

cat my\ notes.txt escapes the space with a backslash.

For anything you create yourself, prefer my-notes.txt or my_notes.txt. Spaces in filenames cause a small tax on every command you will ever run against them.

◈ Graded Task

Take stock of the workspace. Save a list of every JavaScript file anywhere in the tree into js-files.txt in your home directory, and save a list of every directory into dirs.txt. Both lists must come from find rather than being typed by hand.

Checked against the filesystem you leave behind, not the commands you type, so any route that gets the job done counts. 4 visible and 3 hidden checks.

SANKOFA SANDBOX
learner:~$

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Practice Test →
← Back