Skip to content
Advertisement

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

I have a function produce which determines whether a file is present and if not it runs the following command. This works fine when the command output simply writes to stdout. However in the command below I pipe the output to a second command and then to a third command before it outputs to stdout. In this scenario I get the output writing to file correctly but it does not echo the preceding $@ from the produce function and the contents of the initial unpopulated outputfile.vcf (contains header columns) which is generated by the pipeline command on execution is also being outputted to stdout. Is there a more appropriate way to evaluate $@ > "${curfile}"

   produce() {
    local curfile=$1
    #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 -

Advertisement

Answer

Ok as I mentioned in my comment the issue seems to relate to the pipe characters so I had to evaluate the variable using eval and escape the pipe character. So in order to ensure the function produce interprets $@ correctly I fed the command as follows. Note also that the variables are all now quoted

 #######

 produce() {
local curfile="$1"
#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 -
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement