ChrisG
ChrisG

Reputation: 149

Specify multiple directories for recursive search

I have a bash script which searches through all the sub-directories (at all levels) given a target directory:

#! /bin/bash

DIRECTORIES="/home/me/target_dir_1"

for curr in $DIRECTORIES
do
   ...

Now I want the script to search multiple target directories such as target_dir_1, target_dir_2, target_dir_3. How should I modify the script to do this?

Upvotes: 0

Views: 98

Answers (3)

devnull
devnull

Reputation: 123508

Say:

for i in /home/me/target_dir_{1..5}; do
  echo $i;
done

This would result in:

/home/me/target_dir_1
/home/me/target_dir_2
/home/me/target_dir_3
/home/me/target_dir_4
/home/me/target_dir_5

Alternatively, you can specify the variable as an array and loop over it:

DIRECTORIES=( /home/me/target_dir_1 /home/me/target_dir_2 /home/me/target_dir_3 )
for i in ${DIRECTORIES[@]}; do echo $i ; done

which would result in

/home/me/target_dir_1
/home/me/target_dir_2
/home/me/target_dir_3

Upvotes: 2

konsolebox
konsolebox

Reputation: 75488

#!/bin/bash

GIVEN_DIR=$1  ## Or you could just set the value here instead of using $1.

while read -r DIR; do
   echo "$DIR"  ## do something with subdirectory.
done < <(exec find "$GIVEN_DIR" -type d -mindepth 1)

Run with:

bash script.sh dir

Note that word splitting is a bad idea so don't do this:

IFS=$'\n'
for DIR in $(find "$GIVEN_DIR" -type d -mindepth 1); do
   echo "$DIR"  ## do something with subdirectory.
done

Neither with other forms like when you could use -print0 for find, although it's fine if you still use while:

while read -r DIR -d $'\0'; do
   echo "$DIR"  ## do something with subdirectory.
done < <(exec find "$GIVEN_DIR" -type d -mindepth 1 -print0)

Lastly you could record those on an array:

readarray -t SUBDIRS < <(exec find "$GIVEN_DIR" -type d -mindepth 1)
for DIR in "${SUBDIRS[@]}"; do
   echo "$DIR"  ## do something with subdirectory.
done

Upvotes: 3

chickegg
chickegg

Reputation: 105

use find instead.

find /home/me/target_dir_1 -type d

You can put that in a for loop:

for d in target_dir_1 target_dir_2 
do
   find /home/me/"$d" -type d
done

If it is always /home/me, and you want to search all the directories under that, do the follwing:

find /home/me -type d

Upvotes: 3

Related Questions