How to use file contents as command-line arguments?
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.
Some programs use the "@" semantics to feed in args from a file eg. gcc @argfile
Where, for gcc, argfile contains options
-ansi
-I/usr/include/mylib
This can be nested so that argfile can contain
-ansi
-I/usr/include/mylib
@argfile2
http://gcc.gnu.org/onlinedocs/gcc-4.6.3/gcc/Overall-Options.html#Overall-Options
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.
gcc `cat file.with.options`
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))
with bash
gcc $(<file)
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 $#; }
精彩评论