【发布时间】:2021-03-22 23:34:41
【问题描述】:
我正在尝试编写一个代码,该代码在根据用户输入确定的文件列表上运行脚本。由于某种原因,以下代码不起作用?有什么方法可以评估 query_cmd 并遍历它输出的文件。
if [[ $# -gt 0 && "$1" == "--diff" ]]; then
query_cmd="git diff --name-only '*.cc' '*.h'"
else
query_cmd='find . \( -name "*.cc" -o -name "*.h" \)'
fi
while IFS='' read -r line; do
absolute_filepath=$(realpath "$line")
if [[ $absolute_filepath =~ $ignore_list ]]; then
continue
fi
cpp_filepaths+=("$absolute_filepath")
done < <($query_cmd)
【问题讨论】:
-
$(..) 已经对其进行了评估。试试
echo "$query_cmd" -
@thatotherguy 抱歉,我的问题有误。
-
在变量中存储复杂的命令不起作用。要么使用数组,要么将整个
if块放在< <(...)表达式中。见"Why does shell ignore quoting characters in arguments passed to it through variables?" 和BashFAQ #50: I'm trying to put a command in a variable, but the complex cases always fail! -
@MrR,不,由于我描述的原因,它在 OP 的情况下不起作用。在
$query_cmd字符串中包含文字文本'*.cc'意味着命令在解析时需要使用引号。当它们不被解析时,它们被视为文字字符。 -
git expects 形式为
["git", "diff", "--name-only", "*.cc", "*.h"](JSON 转义)的命令行,这是shell 在解析和执行git diff --name-only '*.cc' '*.h'作为代码时将执行的操作。运行$query_cmd将改为运行["git", "diff", "--name-only", "'*.cc'", "'*.h'"],添加 literal 单引号,在正常解析的命令中将被 shell 删除。
标签: bash