Search code examples
bashshellcygwin7zip

Shell script to compress a list of files


I am actually using cygwin64. I would like to compress just a few selected files in a directory. Say, the 3 oldest files in the directory myDir. To get the 3 oldest files, this is what I do:

$ ls myDir -t | tail -3
file1
file2
file3

Now, the question is, how do I pass those 3 file(names) to, say tar or 7z?

Here's what I've tried:

7z a myFile.7z (ls myDir -t | tail -3)

but that doesn't work -- bash complains about the (. Removing it doesn't help, and neither does adding -- after myFile.7z. Same goes for tar instead of 7z.


Solution

  • Use xargs with 7z or tar after the ls/tail command. I don't have a linux terminal now to test but below should work ->

    ls myDir -t | tail -3 | xargs 7z a myFile.7z 
    

    Update -> To resolve path issue, here is the final solution.

    ls -t -d -1 $PWD/myDir/* | tail -3 | xargs 7z a myFile.7z