1

I would like a loop because I have a lot of exclusions. The issue is that I don't know how to use variables to do it.

Here is my code:

tabSearch=("20220514*" "20220508*" "20220515*")
find . \( ! -name "${tabSearch[0]}" -a ! -name "${tabSearch[1]}" \)

The idea is to use as -name $variable as a needed with a loop but I have a syntax issue. Can you help me please?

4
  • 1
    The simplest method is to build another array with the !, -a, etc in addition to the patterns. See "How to use Bash array of globs with find?" Commented Jun 20, 2022 at 6:22
  • 1
    the logic of \( ! -name X -a ! -name X -a ! -name Z \) can be written as ! \( -name X -o -name Y -o -name Z \) Commented Jun 20, 2022 at 6:55
  • 1
    as comment above: ( for glob in "${tabSearch[@]}"; do tests+=(! -name "$glob"); done; find \( "${tests[@]}" \) ) (-a is implied) Commented Jun 20, 2022 at 7:56
  • 1
    What do you mean by syntax issue? I don't see any syntax error in your command. Commented Jun 20, 2022 at 9:49

1 Answer 1

-1

Best to create the condition string separately, then insert into the command.

ALso best to keep each condition separate. Find automatically considers such conditions as 'and'ed unless you specify "-o" .

#!/bin/sh

CONDS=""

for cond in '20220514*' '20220508*' '20220515*'
do
    CONDS="${CONDS} \( ! -name '${cond}' \)"
done

eval find . ${CONDS} -print
Sign up to request clarification or add additional context in comments.

2 Comments

Why is it best to create the condition string separately? What's wrong with the code in the question?
Very old expression about doing things: slice and dice. In other words, keep distinct elements separate. In this case, building the condition string separately from the command that will do things, so that what is being done is more clearly visible.

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.