I would like to add read group info (`-R`) during the mapping/alignment stage as part of my variant calling gatk pipeline.

I am doing something like this:

    bwa mem \
    -M \
    -t 8 \
    -v 3 \
    -R <(sh a-illumina-read-group.sh $1) \
    "$path_dr_bwaindex_genome" \
    $1 $2

where the read group string is generated automatically from the fastq file by the shell script `a-illumina-read-group.sh`. It produces a string like: 

`'@RG\tID:ST-E00215_230_HJ3FMALXX_2\tSM:ST-E00215_230_HJ3FMALXX_2_ATCACG\tLB:ATCACG\tPL:ILLUMINA'`

but, when I run bwa, it fails with this error:
`[E::bwa_set_rg] the read group line is not started with @RG`

I have tried excluding the single quotes (`''`) around read group info, but that didn't change anything. I also tried variations in how the variable is passed.

`-R=$(sh a-illumina-read-group.sh $1) \`

`-R=$(echo $(sh a-illumina-read-group.sh $1)) \`

Just as a test, I tried:

`rg='@RG\tID:ST-E00215_230_HJ3FMALXX_2\tSM:ST-E00215_230_HJ3FMALXX_2_ATCACG\tLB:ATCACG\tPL:ILLUMINA'`

`-R <(echo $rg)  \`

But, they all produce the same error. I would appreciate any solutions to this issue.

I understand that I can add read groups later on using PicardTools `AddOrReplaceReadGroup`, but I thought it might be convenient doing it here in one step.

Thanks.

What worked for me was to read the read group information from the fastq file during the mapping run. My read name in the fastq file looks like this: `@ST-E00274:188:H3JWNCCXY:4:1101:5142:1221 1:N:0:NTTGTA`.

The bash file looks like this:

    #!/bin/bash
    
    header=$(zcat $1 | head -n 1)
    id=$(echo $header | head -n 1 | cut -f 1-4 -d":" | sed 's/@//' | sed 's/:/_/g')
    sm=$(echo $header | head -n 1 | grep -Eo "[ATGCN]+$")
    echo "Read Group @RG\tID:$id\tSM:$id"_"$sm\tLB:$id"_"$sm\tPL:ILLUMINA"
    
    bwa mem \
    -M \
    -t 8 \
    -v 3 \
    -R $(echo "@RG\tID:$id\tSM:$id"_"$sm\tLB:$id"_"$sm\tPL:ILLUMINA") \
    "$path_bwaindex_genome" \
    $1 $2 | samblaster -M | samtools fixmate - - | samtools sort -O bam -o "mapped-bwa.bam"

And the bash file is run as

    bwa-mapper.sh read_1.fq.gz read_2.fq.gz

You can remove this part (`| samblaster -M | samtools fixmate - - | samtools sort -O bam -o`) and replace with `>` if you don't need it. `samblaster` marks duplicates like Picard. I don't remember what `fixmate` does. The sort part sorts the SAM file and generates an output BAM.