tags:

views:

112

answers:

5

I'd like to use arguments from file as command-line arguments for some commands like gcc or ls.

For example gcc -o output -Wall -Werro

as file consist of:

-o output -Wall -Werro

Used for gcc command-line call.

+5  A: 
gcc `cat file.with.options`
ring bearer
Note those are backticks, not single quotes.
tomfanning
+4  A: 

You can use xargs:

cat optionsfile | xargs gcc

Edit: I've been downvoted because Laurent doesn't know how xargs works, so here's the proof:

$ echo "-o output -Wall -Werro" > optionsfile
$ cat optionsfile | xargs -t gcc
gcc -o output -Wall -Werro
i686-apple-darwin10-gcc-4.2.1: no input files

The -t flag causes the command to be written to stderr before executing.

Carl Norum
@Laurent, that is completely false. The command I wrote executes `gcc -o output -Wall -Werro`. Try it yourself if you don't believe it.
Carl Norum
Too bad I can't downvote a comment.
Carl Norum
Or even "xargs gcc < optionsfile".
Sean
@Sean, yup, that's good too.
Carl Norum
Thank You very much. I tried with pipes before, but I didn't know xargs. It will be helpful in future.
morfis
+1  A: 

with bash

gcc $(<file)
ghostdog74
+3  A: 

I recommend using $() along with cat:

gcc $(cat file)

The nice thing about $() over backticks (the classic way) is that it is easier to nest one within another:

gcc $(cat $(cat filename))
R Samuel Klatchko
+1, nesting backticks is a pain.
Carl Norum
+1  A: 

Most of the time, command substitution (either through backticks or $(), as others have pointed out) is fine, but beware of shell expansion rules. Especially, keep in mind that unquoting is done before and word splitting is done after command substitution.

This is not too bad if all your arguments are words but if you start putting spaces or other special characters that would normally need to be quoted into your arguments, then you may meet with strange results (notice the abnormal spacing and quotes in the output):

$ echo "foo 'bar   baz'" >a
$ echo $(cat a)
foo 'bar baz'

Quoting the whole command subtitution is not a solution, obviously, as it would prevent word splitting (hence, your whole file's content would appear as one long argument instead of many options), and would do nothing about the quotes.

$ echo "$(cat a)"
foo 'bar   baz'

One solution around this is to use the eval builtin:

$ eval echo "$(cat a)"
foo bar   baz

N.B.: echo may not be the best example command here; you might want to replace it with something else, e.g. the following function:

$ f() { echo $#; }
rz0