在 bash 中评估代表单个管道命令的两个变量的最佳方法是什么?

What is the best way to evaluate two variables representing a single pipeline command in bash?

我有一个函数 produce 可以确定文件是否存在,如果不存在,则运行以下命令。当命令输出只是写入 stdout 时,这很好用。但是,在下面的命令中,我将输出通过管道传输到第二个命令,然后通过管道传输到第三个命令,然后再输出到标准输出。在这种情况下,我将输出正确地写入文件,但它不会从 produce 函数中回显前面的 $@ 以及由执行时的管道命令也被输出到标准输出。有没有更合适的方法来评估$@ > "${curfile}"

   produce() {
    local curfile=
    #Remove the first element of the list of passed arguments
    shift
    if [ ! -e "${curfile}" ]; then
    #Run the subsequent command as shown in the list of passed arguments
       echo $@
       $@ > "${curfile}"
    fi
    }


   produce outputfile.vcf samtools view -bq 20 input.bam | samtools mpileup -Egu -t DP,SP -f hs37d5formatted.fa -| bcftools call -cNv -

您可以使用 >> 附加到文件。例如:

echo "line 1" >> filename
echo "line 2" >> filename

将生成包含以下内容的文件:

line 1
line 2

好的,正如我在评论中提到的,问题似乎与管道字符有关,因此我不得不使用 eval 评估变量并转义管道字符。因此,为了确保函数 produce 正确解释 $@,我按如下方式输入了命令。另请注意,变量现在都被引用

 #######

 produce() {
local curfile=""
#Remove the first element of the list of passed arguments
shift
if [ ! -e "${curfile}" ]; then
#Run the subsequent command as shown in the list of passed arguments
   echo "$@"
   eval "$@ > ${curfile}"
fi
}


produce outputfile.vcf samtools view -bq 20 input.bam \| samtools mpileup -Egu -t DP,SP -f hs37d5formatted.fa -\| bcftools call -cNv -