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' | sortWith 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 -emptyThis 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
MediumWrite a script that reports the log files and the empty folders under a folder.
- Open
scan.sh. The folder to scan is its first argument. - Print
Logs:, then every file (not folder) under it whose name ends in.log, one path per line, sorted. Theappfolder holds a folder namedarchive.log: it must not be listed, but the files inside it are. - Print
Empty folders:, then every empty folder under it, one per line, sorted. - 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/cacheThen run bash scan.sh app/old: it prints Logs:, app/old/2025.log and Empty folders: with nothing under it.
Try it yourself
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Bash Scripting
1Arguments And Exit Codes
Script ArgumentsAll The ArgumentsExit CodesChecking ArgumentsRecap - Unit Converter5Text Power Tools
Finding FilesBatch Work With xargsEditing Text With sedColumns With awkRecap - Log SummaryPractice on your own: Terminal playground