I\'m writing a bash script which shall search in multiple files.
The problem I\'m encountering is that I can\'t egrep an undetermined number of variables passed as param
A safe eval could be a good solution
#!/bin/bash
if [[ $# -gt 0 ]]; then
TEMP=("grep" "-e" "\"\$1\"" "*")
for (( I = 2; I <= $#; ++I )); do
TEMP=("${TEMP[@]}" "|" "egrep" "-e" "\"\$${I}\"")
done
eval "${TEMP[@]}"
fi
To run it:
bash script.sh A B C
You can use recursion here to get required number of pipes:
#!/bin/bash
rec_egrep() {
if [ $# -eq 0 ]; then
exec cat
elif [ $# -eq 1 ]; then
exec egrep "$1"
else
local pat=$1
shift
egrep "$pat" | rec_egrep "$@"
fi
}
first_arg="$1"
shift
grep "$first_arg" * | rec_egrep "$@"