I love using the following pattern for searching in files:
grep --color=auto -iRnHr --include={*.js,*.html,} --exclude-dir={release,dev,} "span" .
I'd like, however, to have this one wrapped into a bash command like this:
findinfiles {*.js,*.html,} {release,dev,} "span" // syntax is just a guessing
I cannot solve the problem of passing these kinds of braces into a bash function and using them with $1
, $2
and so on. When I use the following:
function findinfiles() {
echo $1, $2, $3
}
Then:
me@pc ~> findinfiles {*.js,*.html,} {release,dev,} "span"
*.js, *.html, release
Of course, passing arguments to grep won't work this way. It seems that arguments are indexed but not properly grouped.
Can anyone teach me how to deal with these kinds of arguments?
Best Answer
When you run
findinfiles {*.js,*.html,} {release,dev,} "span"
, here is what happens:findinfiles
,{*.js,*.html,}
{release,dev,}
span
.findinfiles
,*.js
,*.html
,release
,dev
,span
.*.js
and*.html
to the list of matching file names. If no file name matches either pattern, it is left alone.findinfiles
, finds out that it's a function, and executes the function with the supplied parameters.You can prevent the braces and wildcards from being expanded at the function call, but then the braces will appear literally in the arguments, which isn't particularly useful.
I suggest changing the format of your function call. Instead of using braces, use only commas, and manually split the arguments at commas inside the function.
Explanations:
dirs
to the list of extra parameters. If there are none, use.
(current directory) instead.Set
IFS
to a comma. When a script contains an unquoted variable expansion like$patterns
and$excludes
above, the shell performs the following:IFS
. By default,IFS
contains whitespace characters (space, tab and newline).(To avoid these expansion steps, use double quotes around the variable substitution, as in
patterns="$1"
and so on in the script above.)The function builds the command line to execute incrementally in the array variable
cmd
. At the end, the command is executed.Alternatively, you could build on the following settings:
Run commands like
Explanations:
shopt -s extglob
activates the@(js|html)
form of wildcard pattern, which matches eitherjs
orhtml
. (This option activates other pattern forms, see the manual for details.)shopt -s globstar
actives the pattern**/
which matches subdirectories at any depth (i.e. it performs a recursive traversal).fif_excludes
variable.