pass output as an argument for cp in bash

Yamiko picture Yamiko · Jul 26, 2011 · Viewed 72.1k times · Source

I'm taking a unix/linux class and we have yet to learn variables or functions. We just learned some basic utilities like the flag and pipeline, output and append to file. On the lab assignment he wants us to find the largest files and copy them to a directory.

I can get the 5 largest files but I don't know how to pass them into cp in one command

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

Answer

Diego Sevilla picture Diego Sevilla · Jul 26, 2011

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.