1

I have a bash command built from an array as following:

cmd=(java -Xmx8g -jar program.jar input.vcf ">" output.vcf) 

I do not have problems when using echo:

echo "${cmd[@]}" java -Xmx8g -jar program.jar input.vcf > output.vcf 

But when I run it using:

"${cmd[@]}" 

The > is ignored and I cannot redirect stdout to output.vcf file.

Please, could you suggest me a solution?

5
  • 1
    When you pass it that way, the > isn't ignored; instead, it's passed to the Java program as an argument. Commented Sep 19, 2014 at 23:47
  • That's a (security and correctness) feature, not a bug -- it means that data (like arguments) can't be treated as code without intentional action to the contrary. Commented Sep 19, 2014 at 23:48
  • You could use eval "${cmd[@]}". Commented Sep 19, 2014 at 23:49
  • @ooga, ...thereby completely bypassing said security, and also losing any advantage from using proper array expansion syntax. Commented Sep 19, 2014 at 23:49
  • 1
    BTW, the answer provided by @JohnKugelman is echoed as a best practice by BashFAQ #50: mywiki.wooledge.org/BashFAQ/050 Commented Sep 19, 2014 at 23:52

2 Answers 2

4

It would be better to store the command in a function. Functions are for commands, variables are for data.

cmd() { java -Xmx8g -jar program.jar input.vcf > output.vcf } cmd 

(I implore you not to use eval, which allow your variable-based approach to work, but opens up a whole other can of worms.)

Sign up to request clarification or add additional context in comments.

Comments

2

I would prefer John Kugelman's answer but if you really mean to execute the words stored in the array, you could eval them:

cmd=(date '>' date.stdout) eval "${cmd[@]}" 

Be warned that this might open up all kinds of security holes.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.