🎓 A1Learner
🔍
0 of 46 lessons completed

Bash Find with Exec

Find searches a directory tree and acts on each match. The -exec action runs a command once for every file it finds.

find -exec runs a command on each match

Three text files and one log file are created. Find matches only the text files, and basename prints each match name in sorted order.

printf "x\n" > a.txt
printf "x\n" > b.txt
printf "x\n" > c.txt
printf "x\n" > notes.log
find . -name "*.txt" -exec basename {} \; | LC_ALL=C sort

-print0 keeps spaced names whole

Two files with spaces in their names are created. Each printed line is one whole name, so neither name is split at its space.

printf "x\n" > "red file.txt"
printf "y\n" > "blue file.txt"
find . -name "*.txt" -print0 | LC_ALL=C sort -z | while IFS= read -r -d '' f; do name=$(basename "$f"); echo "seen $name"; done

-delete removes only the matched files

One file to keep and two temporary files are created. Find deletes only the temporary files, and the kept file remains.

printf "keep\n" > keep.txt
printf "junk\n" > junk1.tmp
printf "junk\n" > junk2.tmp
find . -name "*.tmp" -delete
if [ -f keep.txt ]; then echo "keep file remains"; fi
ls *.tmp 2>/dev/null || echo "no tmp files left"

Example

printf "alpha line\n" > report-a.txt
printf "beta line\n" > report-b.txt
printf "log line\n" > notes.log
find . -name "report-*.txt" -exec cat {} \; | LC_ALL=C sort

Key points

  • find: a command that walks folders and lists files that match a test.
  • -name: a test that matches a file name pattern, such as *.txt.
  • -exec ... {} \;: an action that runs a command with each match in place of {}.
  • -print0: an output form that ends each name with a zero byte instead of a newline.
  • A zero byte is safe in names with spaces, where a plain newline would split them.
  • -delete: an action that removes only the files find matched.

In this example, two report files and one log file are created. Find matches only the report files, and -exec runs cat on each match. Sorting the printed lines puts them in a fixed order, and the log file stays out.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does -print0 protect against?