问题
I'm looking for a unix shell command to append the contents of a file as the parameters of another shell command. For example:
command << commandArguments.txt
回答1:
xargs was built specifically for this:
cat commandArguments.txt | xargs mycommand
If you have multiple lines in the file, you can use xargs -L1 -P10
to run ten copies of your command at a time, in parallel.
回答2:
xargs takes its standard in and formats it as positional parameters for a shell command. It was originally meant to deal with short command line limits, but it is useful for other purposes as well.
For example, within the last minute I've used it to connect to 10 servers in parallel and check their uptimes:
echo server{1..10} | tr ' ' '\n' | xargs -n 1 -P 50 -I ^ ssh ^ uptime
Some interesting aspects of this command pipeline:
- The names of the servers to connect to were taken from the incoming pipe
- The
tr
is needed to put each name on its own line. This is becausexargs
expects line-delimited input - The
-n
option controls how many incoming lines are used per command invocation.-n 1
says make a newssh
process for each incoming line. - By default, the parameters are appended to the end of the command. With
-I
, one can specify a token (^
) that will be replaced with the argument instead. - The
-P
controls how many child processes to run concurrently, greatly widening the space of interesting possibilities..
回答3:
command `cat commandArguments.txt`
Using backticks will use the result of the enclosed command as a literal in the outer command
来源:https://stackoverflow.com/questions/11918580/appending-file-contents-as-parameter-for-unix-shell-command