Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/reporting-services/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么在find中使用bash变量会失败?_Bash_Find - Fatal编程技术网

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

为什么在find中使用bash变量会失败?,bash,find,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'

我在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:

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

不,你不能就这样做$假定pathVar是单个参数。您可以使用eval将字符串作为命令执行,或者更好的是,使用条件检查运行完整的命令来决定执行哪个命令。什么定义了“单个参数”?它是否只是一个没有空格的字符串值?如果我最初的问题中的pathVar不是常量用户输入、来自另一个进程的结果等,该怎么办?我如何动态构建这个find命令?没关系,我可以只使用cmd=$cmd$pathVar来获得带有动态变量的行为。