I'm trying to write a code search script, with configurable directories and files that are excluded. The main part of this script is the following line:
out=$(grep -TInr$C$W --color=always \
--exclude={translations} \
--exclude-dir={build,tmp} \
"$SEARCH")
The $C
and $W
variables are set by script parameters to configure case insensitivity and exact word matching, and $SEARCH
is simply the remaining parameters, which will be the search string. However, my implementation to ignore certain files does not quite work yet.
To exclude files from search, I'm trying to use a ~/.codesearch_config
file, which looks like this:
#!/bin/bash
if [[ $PWD == "$HOME/project"* ]]; then
exclude_directories={.git,build,tmp}
exclude_files={translations}
fi
The idea here, of course, is that depending on your current working directory, a certain set of excludes will be loaded. But when trying to add these to the script as such:
--exclude=$exclude_files
the whole parameter will be put in single quotes by bash (tested with the -x
option to debug) like this:
grep -TInrw --color=always '--exclude={translations}' '--exclude-dir={build,tmp}' search_term
What I want it to do is expand that to --exclude-dir=build --exclude-dir=tmp
. If I manually add the values of those $exclude_
variables to the command, it expands just fine; The issue is just that the single quotes are placed around my parameter and glob. How can I prevent this?
eval
to expand the whole line before executing it, e.g.$out=(eval "grep ...")
, however, this works only if your input is trusted. – galaxy Apr 04 '16 at 12:15exclude_directories=(.git build tmp)
, and then expand them into--exclude-dir
and--exclude
options (note the plural in options, one for each element of the arrays) in a loop later. – cas Apr 04 '16 at 13:32