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 ?

2

1 Answer 1

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™!

Sign up to request clarification or add additional context in comments.

3 Comments

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, ...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.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.