【发布时间】:2015-01-01 11:51:37
【问题描述】:
我正在编写一个包含 find 命令的脚本,以在给定目录下搜索特定的源文件类型。一个示例调用是:
./find_them.sh --java --flex --xml dir1
上面的命令会在 dir1 下搜索 .java、.as 和 .xml 文件。
要手动执行此操作,我想出了以下查找命令:
find dir1 -type f -a \( -name "*.java" -o -name "*.as" -o -name "*.xml" \)
当我在一个脚本中执行此操作时,我希望能够指定不同的文件集来搜索您,最终得到以下结构:
find_cmd_file_sets=$(decode_file_sets) # Assume this creates a string with the file sets e.g. -name "*.java" -o -name "*.as" etc
dirs=$(get_search_dirs) # assume this gives you the list of dirs to search, defaulting to the current directory
for dir in $dirs
do
find $dir -type f -a \( $find_cmd_file_sets \)
done
上述脚本的行为与预期不符,您执行了该脚本,并且 find 命令搅动了一段时间,然后没有返回任何结果。
我确定我创建的 decode_file_sets 和 get_search_dirs 的等价物正在生成正确的结果。
一个更简单的例子,如果直接在 bash shell 中执行以下操作
file_sets=' -name "*.java" -o -name "*.as" '
find dir -type f -a \( $file_sets \) # Returns no result
# Executing result of below command directly in the shell returns correct result
echo find dir -type f -a \\\( $file_sets \\\)
我不明白为什么 find 命令括号中的变量扩展会改变结果。如果有什么不同,我在 Windows 下使用 git-bash。
这真是令人沮丧。任何帮助将非常感激。最重要的是,我想了解为什么 $file_sets 的变量扩展会表现得如此。
【问题讨论】:
-
为什么你认为变量中的引号与命令行中的引号相同?
-
我不知道是什么让你认为我相信这一点。我正在使用单引号,因此当用作 find 的参数时应保留变量中的双引号
-
我猜for循环有错误——应该是for dir in $dirs
-
@ahjmorton 参数中存储的双引号不用于引用
*.java;他们按字面意思对待。你不能像这样嵌套句法引号。bash数组的引入正是出于这个原因。