0

I have a questions about bash script, i want to put part of find expression to variable. I show on example better what i want to. I have something like this:

find $DIR -type f -name "$NAME" $SIZE $CONTENT_COM;;

and i want to put into $CONTENT_COM something like this: (exactly like this)

-exec grep -l "$CONTENT" {} +

For $SIZE i made this:

SIZE=${SIZE/$SIZE/-size $SIZE};

and i wanted to make this for $CONTENT_COM (it looks similar to what i want, just change -size $SIZE etc to look like this

CONTENT_COM=${CONTENT_COM/$CONTENT/-exec grep -l "$CONTENT" {} +} 

but it doesnt work. ({} +} <---- error in editor) Is there any way to put such expression to variable then use it ?

Kawson
  • 138
  • 1
  • 10
  • See [BashFAQ #50](http://mywiki.wooledge.org/BashFAQ/050) -- *I'm trying to put a command in a variable, but the complex cases always fail!* – Charles Duffy Mar 27 '21 at 01:01
  • Possible duplicate of ["Why does shell ignore quoting characters in arguments passed to it through variables?"](https://stackoverflow.com/questions/12136948/why-does-shell-ignore-quoting-characters-in-arguments-passed-to-it-through-varia) (which is itself marked as a duplicate, but the other is significantly different). – Gordon Davisson Mar 27 '21 at 02:50

1 Answers1

2

Yes, you can use arrays to build up commands with arbitrary arguments, for example:

search_term='some regex'
content_command=('grep' '-l' "$search_term")
find . -exec "${content_command[@]}" {} +

Also, Use More Quotes™!

l0b0
  • 55,365
  • 30
  • 138
  • 223
  • Thanks! It helped me alot. I can't do -exec outside the array because not every time i want to exec it, but solution was for sure a little bit different (from link you post): CONTENT_COM=(\( -exec grep -l "$CONTENT" {} + \)) [\ before ( and ) but comments delete it] – Kawson Mar 27 '21 at 00:32
  • 1
    @Kawson, ...that's a bit confusing. It should only be one `(` and one `)`, not doubled, and no backslashes. (Doubling `((` and `))` is the syntax for starting and ending an arithmetic context; it does a very different thing). The syntax in this answer is exactly correct just as it is. – Charles Duffy Mar 27 '21 at 01:02
  • @Kawson You can use backticks to mark code in comments. Are you trying to include literal parentheses in the array (i.e. to include them in the `find` expression), like `CONTENT_COM=( \( -exec grep -l "$CONTENT" {} + \) )`? You shouldn't need to, since the whole `-exec ... +` expression is a single logical item in the `find` expression. – Gordon Davisson Mar 27 '21 at 02:52