简体   繁体   中英

Pass variable value to --include argument using grep command inside bash script

I want to pass to grep command (inside a bash script), the file extensions to search, using --include argument. These file extensions will be entered by user from command line as an argument (4th argument holds files extensions, in a comma separated way).

This is my script:

...
echo "Searching in ${4} files for pattern"
egrep -irn . --include=\*.{"${4}"} --exclude=\*.{class} -e "${3}"
...  

I also tried creating a String with the command, and calling eval, like this:

...
comando="egrep -irn . --include="\\*.{${4}}" --exclude=\*.{class} -e "${3}""
echo $comando
resultado=eval $comando
echo $resultado

(when echoing comando i get this: egrep -irn . --include=*.{wsdl,xml} --exclude=*.{class} -e texto , which is exactly the commando that if executed in command line returns some matches.)

I also tried passing a variable with all the include argument:

...
argumento="\\*.{${4}}"
egrep -irn . --include=$argumento --exclude=\*.{class} -e "${3}"
...

This is how the script is called from command line:

sh ./searchRecursiveIterativeEgrep.sh /tmp/test/another/ /usr/local/aux/ "texto" wsdl,xml

Any ideas on how to achieve this? Thank you

I just understood why you had a problem: If I copy/paste the generated command, it works but within a shell it doesn't.

So I propose that as a workaround

argumento="\\*.{${4}}"
echo egrep -irn . --include=$argumento --exclude=\*.{class} -e "${3}" | sh

(piping the echo to a new shell does it: it works). Maybe it's not the best answer but it does the job.

Maybe someone can explain that, or come out with a better, cleaner answer.

You didn't provide any sample input or expected output so this is obviously untested but the right approach is to use find to FIND files and grep to G lobally search for a R egular E xpression in a file and P rint the matching text (see the hints in their names ;-) ). Something like:

find . -type f -name "*.$4" -print0 | xargs -0 grep -Ein "$3"

man find, xargs, and grep for details.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM