Home > Net >  Simple Bash Script that recursively searches in subdirs for a certain string
Simple Bash Script that recursively searches in subdirs for a certain string

Time:05-01

i recently started learning linux because a ctf contest is coming in the next months. The problem that I struggle with is that i am trying to make a bash script that starts from a directory, checks if the content is a directory or other kind of file. If it is a file,image etc apply strings $f | grep -i 'abcdef', if it is a directory cd to that directory and start over. i have c experience and i understand the logic but i can't really make it work.I can't succesfully implement the loop that goes thru all the subdirectories. All help would be appreciated!

CodePudding user response:

you don not need a loop for this implementation. The find command can do what you are looking after. for instance:

 find /home -type f -exec sh -c " strings {} | grep abcd " \;

explain:

/home is you base directory can be anything

-type f: means a regular file

-exec from the man page:

"Execute command; true if 0 status is returned. All following arguments to find are taken to be arguments to the command until an argument consisting of ;' is encountered. The string {}' is replaced by the current file name being processed everywhere it occurs in the arguments to the command, not just in arguments where it is alone, as in some versions of find. Both of these constructions might need to be escaped (with a `') or quoted to protect them from expansion by the shell. See the EXAMPLES section for examples of the use of the -exec option. The specified command is run once for each matched file. The command is executed in the starting directory. There are unavoidable security problems surrounding use of the -exec action; you should use the -execdir option instead."

CodePudding user response:

Suggesting a grep command on find filter results:

 grep "abcd" $(find . -type f)
  • Related