stanedav
stanedav

Reputation: 476

Bash - pass argument from array

I am using bash to call tool written in java (gatk) and I need to pass multiple arguments from array as input arguments. I tried it this way, but it seems not working. Could you please help me, how to solve it?

Code:

java $GATK \
    -T GenotypeGVCFs  \
    -R $ref \
    -o output.vcf \
    for foo in array
    do
        --variant  $foo \
    done

What i want to be called:

java $GATK \
    -T GenotypeGVCFs  \
    -R $ref \
    -o output.vcf \
    for foo in array
    do
        --variant  file1 \
        --variant  file2 \
        --variant  file3 ...etc
    done

edit: sorry for misunderstandings

array=("file1","file2","file3"...)

Thanks

Upvotes: 2

Views: 141

Answers (4)

glenn jackman
glenn jackman

Reputation: 246754

@RealSkeptic's answer is the best. I'd write, for readability:

array=( "file 1" "file 2" "file 3" )
args=(
    "$GATK"
    -T GenotypeGVCFs 
    -R "$ref"
    -o output.vcf
)
for foo in "${array[@]}"; do args+=( --variant "$foo" ); done

java "${args[@]}"

Upvotes: 0

RealSkeptic
RealSkeptic

Reputation: 34618

I assume that what you actually want is that if array contains a b c, to have the command

java $GATK \
    -T GenotypeGVCFs  \
    -R $ref \
    -o output.vcf \
    --variant a --variant b --variant c

If that is so, you can prepare a second array:

array=("file 1" "file 2" "file 3")
declare -a fullarray
for i in "${array[@]}"
do
    fullarray+=( --variant "$i" )
done

And then

java $GATK \
    -T GenotypeGVCFs  \
    -R $ref \
    -o output.vcf \
    "${fullarray[@]}"

This will also make sure that if any of the names in array contains a space, it will still be passed as a proper parameter and not split into two (assuming that you didn't mess it up when you added it to the array).

Upvotes: 5

wich
wich

Reputation: 17117

You can do this with the following:

java $GATK \
    -T GenotypeGVCFs  \
    -R $ref \
    -o output.vcf \
    ${array[*]/#/ --variant }

Upvotes: 0

Tamar
Tamar

Reputation: 679

With echo and $():

array=(file1 file2 file3)
java $GATK \
    -T GenotypeGVCFs  \
    -R $ref \
    -o output.vcf \
    $(for foo in ${array[*]}
    do
        echo -n " --variant  $foo"
    done)

Upvotes: 0

Related Questions