I try to code a bash 4 (or sh, if that’s possible) script that does the following: 1st parameter: the path to the compressed modules to search, could be “.” 2nd the search pattern to look for
The script so far looks like this (be aware that it is not foolproof, it not checks if both parameters are valid, it not even checks if 2 parameters are given at all, all that I would add if I get the script to work as I want it to)
#!/bin/bash for module in $(find $1 -type f -name "*.xzm"); do echo $module lsxzm $module | grep "$2" done
lsxzm is a script that lists the contents of the compressed live Linux module. Now, a possible result for such a search would look like so (lets consider I saved the script as “/usr/local/bin/lsxzmgrep” and made it executable):
/porteus/base# lsxzmgrep . libtiff.so.3 ./000-kernel.xzm ./001-core.xzm /usr/lib64/libtiff.so.3 /usr/lib64/libtiff.so.3.9.7 ./001-de-core_locales.xzm ./002-xorg.xzm ./003-xfce.xzm ./010-nvidia-304.137-k.4.16.3-x86_64-don.xzm
I would like to have only this output:
/porteus/base# lsxzmgrep . libtiff.so.3 ./001-core.xzm /usr/lib64/libtiff.so.3 /usr/lib64/libtiff.so.3.9.7
How can this be done? All I can think of is temporarily buffering the output of each grep from the for do done loop, and only print it together with the name of the module when grep did find something, done by examining the $? of grep.
But that would be a less than elegant solution.
Now I wonder, is a shell script, especially for bash 4, able to get the same result without the need of buffering the grep result and examining the return value of the grep command to get the same result: only print the name of the module and the listed file name(s) when the grep command did actually find something?
Advertisement
Answer
You should first get the grep results, then print data out:
#!/bin/bash for module in $(find $1 -type f -name "*.xzm"); do result=$(lsxzm $module | grep "$2") if [ $? -eq 0 ]; then # grep returned OK, write out results echo $module echo "$result" fi done
To do this, the output of grep is stored into a variable “result”. The exit status is checked; if it is 0 (ok), then grep succeeded (in finding the search string), so data is printed out.