Menu
CoddyTech

Finding Files

Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 22 of 39.

find searches a folder and every folder inside it, and prints each path that passes the tests you give it. The first argument is where to start.

find photos -name '*.jpg' | sort

With photos/beach.jpg and photos/trip/hill.jpg on disk, this prints both paths, the nested one too. Quote the pattern so the shell hands it to find instead of expanding it. find prints paths in the order the disk returns them, which can change, so pipe them through sort when order matters.

More tests: -type f keeps files, -type d keeps folders, -empty keeps empty files and folders, and -size +1M keeps files larger than one megabyte (k counts kilobytes). Several tests in a row must all pass.

find photos -type d -empty

This prints photos/raw, a folder with nothing in it. -exec runs a command on each match: {} becomes the path and \; ends the command.

find photos -name '*.txt' -exec wc -l {} \;

It prints 3 photos/captions.txt.

challenge icon

Challenge

Medium

Write a script that reports the log files and the empty folders under a folder.

  1. Open scan.sh. The folder to scan is its first argument.
  2. Print Logs:, then every file (not folder) under it whose name ends in .log, one path per line, sorted. The app folder holds a folder named archive.log: it must not be listed, but the files inside it are.
  3. Print Empty folders:, then every empty folder under it, one per line, sorted.
  4. Save the file.

Try it: run bash scan.sh app. It prints:

Logs:
app/access.log
app/archive.log/jan.log
app/error.log
app/old/2025.log
Empty folders:
app/cache

Then run bash scan.sh app/old: it prints Logs:, app/old/2025.log and Empty folders: with nothing under it.

Try it yourself

Terminal
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Bash Scripting

Practice on your own: Terminal playground