为什么在find中使用bash变量失败?

时间:2019-04-15 13:33:38

标签: bash find

我在bash脚本中有一个find命令,该命令可以正常工作,但是当我尝试将其分解为变量并添加在一起时,它将不再正常工作。

我并不是真的在寻找一种更好的方法,我想了解Bash在这种情况下正在做些什么,因为对此我感到很沮丧。

# 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"

1 个答案:

答案 0 :(得分:1)

如评论中所述,

选项1:

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

选项2:

if [[<condition to run long command>]]; then
    find . -type f -name 'config' ! -path './.git*'
    # ...
else
    find . -type f -name 'config'
    # ...
fi