Is there a way to pass multiple arguments in the middle of a command using xargs?

For example, I have a file javaoptions.txt which contains a default set of Java options. I would like to be able to do something like

xargs -I % java % ClassName < javaoptions.txt

and have it pass all of the options in to one command. If I try doing this, however, it uses several commands, passing one option in each time.

For what it's worth, I cannot modify the source code that is being executed


If I understand you correctly, you just want to insert the contents of javaoptions.txt into your java command. If so, xargs is no help. That's for running the same command on each line of output of another command. All you need here is

java $(cat javaoptions.txt) ClassName

Personally, however, I would write a function for this:

   javaOpts="-Xmx4g -Djava.io.tmpdir=/tmp/foo" ## random example
   java $javaOpts "$@"  ## run the java command with the options    

Add that to your ~/.bashrc (or equivalent for your shell) and you can run:

runJava Classname

To run

java -Xmx4g -Djava.io.tmpdir=/tmp/foo Classname
  • javaOpts should either be an array (and used as "${javaOpts[@]}", or there shouldn't be double-quotes around it on the java ... line. With the double-quotes, $javaOpts is treated as a single argument to java, not multiple arguments. i.e. it's effectively -X'mx4g -Djava.io.tmpdir=/tmp/foo' and will result in a fatal error resembling Invalid maximum heap size: -Xmx4g -Djava.io.tmpdir=/tmp/foo (exact error msg will vary depending on java implementation and/or version). Using vars for args like this is one of the very few situations where you shouldn't double-quote your variables. – cas Apr 14 '16 at 23:36
  • @cas D'oh! Of course, that's what I get for being in a hurry. Thanks, fixed. – terdon Apr 15 '16 at 8:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.