Reputation: 1544
I'm trying to write a bash script to search my source directories for a string using grep
-- and no, I can't use ack
.
The directory structure is
Headers: .../product/package/product-module/i/filename.h
Source: .../product/package/product-module/s/filename.c
I'd like the option to specify module or not (search all modules), which is the point of argument $2
. Problem is, I can't get either *$2
or "*$2"
to work in the script (please see below).
edit: The former attempt results in no output whatsoever, and the latter results in "grep: No such file or directory"
How do I correctly use *
with grep
if I want to compound it with another string?
#!/bin/bash
# Usage: search_src -[si] < module | all > < target >
if [ $1 == "-s" ]; then
fext="c"
subdir="s"
elif [ $1 == "-i" ]; then
fext="h"
subdir="i"
else
fext="[ch]"
subdir="[si]"
fi
if [ $2 == "all" ]; then
module=*;
else
module=*$2;
fi
shift 2;
grep \"$@\" ~/workspace/*/package/$module/$subdir/*.$fext
Upvotes: 1
Views: 287
Reputation: 75488
Just use a safe eval and some minor modifications:
#!/bin/bash
# Usage: search_src -[si] < module | all > < target >
if [[ $1 == "-s" ]]; then
fext="c"
subdir="s"
elif [[ $1 == "-i" ]]; then
fext="h"
subdir="i"
else
fext="[ch]"
subdir="[si]"
fi
if [[ $2 == "all" ]]; then
module='*';
else
module='*"$2"';
fi
shopt -s nullglob
eval "files=(~/workspace/*/package/$module/$subdir/*.$fext)"
IFS=$' \t\n'
[[ $# -gt 2 && ${#files[@]} -gt 0 ]] && grep -e "${*:3}" -- "${files[@]}"
Upvotes: 3