Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using file contents as command line arguments in BASH

Tags:

redirect

bash

I'd like to know how to use the contents of a file as command line arguments, but am struggling with syntax.

Say I've got the following:

# cat > arglist
src/file1 dst/file1
src/file2 dst/file2
src/file3 dst/file3

How can I use the contents of each line in the arglist file as arguments to say, a cp command?

like image 523
Jamie Avatar asked Nov 04 '09 14:11

Jamie


2 Answers

the '-n' option for xargs specifies how many arguments to use per command :

$ xargs -n2 < arglist echo cp

cp src/file1 dst/file1
cp src/file2 dst/file2
cp src/file3 dst/file3
like image 66
matja Avatar answered Nov 09 '22 15:11

matja


Using read (this does assume that any spaces in the filenames in arglist are escaped):

while read src dst; do cp "$src" "$dst"; done < argslist

If the arguments in the file are in the right order and filenames with spaces are quoted, then this will also work:

while read args; do cp $args; done < argslist
like image 32
Stephan202 Avatar answered Nov 09 '22 15:11

Stephan202