Linux – passing variables from ‘ls’ to ‘tar’ via ‘xargs’

linuxlstarxargs

I am trying to do something like

ls -t | head -n 3 | xargs -I {} tar -cf t.tar {}

to archive the 3 last modified files but it ends up running the tar command separately for each of the files and at the end I am left with one tar file containing the last of the 3 files (in their whatever order). I know I am not using 'xargs' correctly but searching did not help; I find examples that do not work either. Even the simpler command

ls | xargs -I {} tar -cf t.tar {}

ends up with a tar file that contains only one of the files in that directory.

Best Answer

ls -t | head -n 3 | xargs tar -cf t.tar

Works for me. Is there a reason you need the -I flag set?

Related Question