0

I've got a find command in a bash script that works, but when I try to break it into variables that get added together it no longer works correctly.

I'm not really looking for a better way of doing this, I'd like to understand what Bash is doing in this case as I'm very stumped at this.

# Works, prints ./config
find . -type f -name 'config' ! -path './.git*'

echo
pathVar="! -path './.git*'"
# Doesn't correctly ignore './.git/config'
find . -type f -name 'config' $pathVar

echo
# Doesn't work 'find: ! -path './.git*': unknown primary or operator'
find . -type f -name 'config' "$pathVar"
2
  • 1
    No, you can't do it simply like that. $pathVar is assumed to be a single argument. you may either use eval to execute a string as a command or better yet, run the complete commands using conditional checks to decide which command the execute. Commented Apr 15, 2019 at 13:43
  • What defines a 'single argument'? Would it just be a string value with no spaces? Commented Apr 15, 2019 at 14:43

1 Answer 1

1

As stated in the comments,

Option 1:

cmd="find . -type f -name 'config'"
if [[<condition to run long command>]]; then
    cmd="$cmd ! -path './.git*'"
fi
eval $cmd

Option 2:

if [[<condition to run long command>]]; then
    find . -type f -name 'config' ! -path './.git*'
    # ...
else
    find . -type f -name 'config'
    # ...
fi
Sign up to request clarification or add additional context in comments.

2 Comments

What if the pathVar from my original question isn't something constant (user input, result from another process etc). How could I build up this find command dynamically?
Never mind, I can just cmd="$cmd $pathVar" to get that behavior with a dynamic variable.

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.