Rory Fielding
Rory Fielding

Reputation: 110

Recursively traversing folders to execute an if statement

I'm trying to create a shell script which recursively traverses folders in directories, checks if a file exists, and if it does exist - execute a second script.

I've been able to recursively traverse through the folders and log the current directory, however including an if statement in this command seems to break the process as I think I am misunderstanding syntax.

The following works:

find . -maxdepth 3 -type d \( ! -name . \) -exec bash -c "cd '{}' && pwd" \;

However doing this gives me a syntax error on line 3, but I can't figure out why?

find . -maxdepth 3 -type d \( ! -name . \) -exec bash -c "cd '{}' && 
if [\(-f "$FILE"\)]; then
sh script.sh" \;

If anyone could provide any help as to what is wrong with the syntax on line 3, it would be greatly appreciated!

Upvotes: 2

Views: 51

Answers (1)

Asensi
Asensi

Reputation: 163

The if needs a fi, and the quotes must be escaped (using \"). While we are at it, the second \( \) aren't needed. You can try:

find . -maxdepth 3 -type d \( ! -name . \) -exec bash -c "cd '{}' && if [ -f \"$FILE\" ]; then sh script.sh; fi" \;

and if it complains about not finding script.sh, the full path to script.sh can be used (instead of just script.sh).

Upvotes: 1

Related Questions