brucezepplin
brucezepplin

Reputation: 9752

recursively call a program to run on each subdirectory

I have a program which does something like

#!bin/bash

cd $1

tree $1

Where I run:

myprogram.sh subdir1

Where subdir1 is a subdirectory of dir I however have subdir1, subdir2, subdir3... subdirN within dir.

How can I tell my program to run on every sub directory of dir? Obviously my program doe not just run tree but just to denote I pass a subdirectory through the command line, of which my program uses the subdirectory name for a numer of processes.

Thanks

Upvotes: 0

Views: 177

Answers (1)

Eric
Eric

Reputation: 1511

Use find. For example find $1 -type d will return a list of all directories under $1, recursing as needed.

You can use it before your script with xargs or exec:

find DIR -type d -print0 | xargs -0 -n1 thescript.sh

or

find DIR -type d -exec thescript.sh {} \;

Both of the above are safe for strangely named directories.

If you want to use find inside your script and no directory names contain newlines, try:

#!/bin/bash
find "$1" -type d| IFS='' while read d; do
   pushd "$d" #like cd, but remembers where you came from

   tree "$d"; #<-- your code here

   popd #go back to starting point
done

If you only want direct subdirectories of the starting point, try adding -depth 1 in the argument list to find in the above examples.

Upvotes: 1

Related Questions