Linux Shell Script Files and Directory Loop

directorylinuxloopsshell

I want to write a shell script in Linux that loops through all directory and sub-directories and cat all text files once. below is what i got so far, im a little behind logic on this one. can someone give me a hand? thanks

the script take 1 argument
eg: ./script.sh directoryName

#!/bin/bash

echo "Directory $1"

cd $1
for f in *.txt
do
cat $f
done

im unsure how to go into sub directories from here, as there can be infinite amount in each sub-directory.

Best Answer

Use find.

If your operating system supports a modern version of POSIX:

find "$1" -type f -name '*.txt' -exec cat '{}' +

...or, if it doesn't:

find "$1" -type f -name '*.txt' -exec cat '{}' ';'

...or, if you want to be inefficient (or have a more interesting use case you haven't told us about), and your find supports -print0...

find "$1" -type f -name '*.txt' -print0 | \
  while IFS='' read -r -d '' filename; do
    cat "$filename"
  done

Don't leave out the -print0 -- otherwise, maliciously-named files (with newlines in their names) can inject arbitrary names into your stream (at worst), or hide from processing (at best).