pass output as an argument for cp in bash [duplicate] pass output as an argument for cp in bash [duplicate] linux linux

pass output as an argument for cp in bash [duplicate]


It would be:

cp `ls -SF | grep -v / | head -5` Directory

assuming that the pipeline is correct. The backticks substitute in the line the output of the commands inside it.

You can also make your tests:

cp `echo a b c` Directory

will copy all a, b, and c into Directory.


I would do:

cp $(ls -SF | grep -v / | head -5) Directory

xargs would probably be the best answer though.

ls -SF | grep -v / | head -5 | xargs -I{} cp "{}" Directory


Use backticks `like this` or the dollar sign $(like this) to perform command substitution. Basically this pastes each line of standard ouput of the backticked command into the surrounding command and runs it. Find out more in the bash manpage under "Command Substitution."

Also, if you want to read one line at a time you can read individual lines out of a pipe stream using "while read" syntax:

ls | while read varname; do echo $varname; done