在bash中的while循环中评估命令



我正试图编写一段代码,在根据用户输入确定的文件列表上运行脚本。出于某种原因,以下代码不起作用?有没有任何方法可以评估querycmd并迭代它输出的文件。

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)

通常,如果您有稍后要运行的代码,您会将其放在函数中,而不是字符串中:

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
...
done < <(query_cmd)

但是,如果你喜欢额外的逃跑挑战,你可以使用字符串并用eval:来评估它们

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
...
done < <(eval "$query_cmd")

最新更新