LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Command to make a script running from every subdir (https://www.linuxquestions.org/questions/programming-9/command-to-make-a-script-running-from-every-subdir-4175714491/)

BudiKusasi 07-10-2022 09:51 PM

Command to make a script running from every subdir
 
How is the find command (or else if better) to let us run a script from, i.e. relative to, every subdir under, and including, current working directory ?

illustratio e.g. script is
Code:

grep 'foo' *

rknichols 07-10-2022 10:20 PM

Code:

find . -type d -exec sh -c 'cd {}; grep foo *' \;
Note that you have to execute a shell in order to expand the "*" in the target directories. Without that, the find command will just pass a literal "*" to the grep (or whatever) command, which will just complain that it can't find any file named "*".

I originally had a much more complex example using "-execdir", but found things were much simpler without it.

grail 07-10-2022 10:22 PM

Not sure I follow but you can use -R option in grep to recurse subdirs

rknichols 07-10-2022 10:39 PM

I believe grep was just an example, not the actual intended command.

fatmac 07-11-2022 03:42 AM

Run the command 'recursively'.

MadeInGermany 07-11-2022 05:59 AM

Within the shell script filenames should be in quotes, and exit the cd status should matter.
Code:

find . -type d -exec sh -c 'cd "{}" && grep foo *' \
Code:

find . -type d -exec sh -c 'cd "{}" && pwd' \;
Portable (all find versions) is
Code:

find . -type d -exec sh -c 'cd "$0" && pwd' {} \;
or
Code:

find . -type d -exec sh -c 'cd "$1" && pwd' chdir.sh {} \;

rtmistler 07-11-2022 08:41 AM

Quote:

Originally Posted by BudiKusasi (Post 6366822)
How is the find command (or else if better) to let us run a script from, i.e. relative to, every subdir under, and including, current working directory ?

Trying to modify this to be a coherent question:
Quote:

How can the find command run a script against all of the found results?
All I have here is about the same with rknichols said in post #2, in fact that's my daily use of find.
As cited, you can run a script using the -exec argument.

Does that solve what you're trying to do? If not, maybe a more clear question?

dugan 07-11-2022 09:10 AM

Code:

grep -R foo
Your example should probably have used a different command.


All times are GMT -5. The time now is 03:51 PM.