dabadaba
dabadaba

Reputation: 9532

How to tar the n most recent files

I am trying to create a script that foreach directoy in the folder folder, only the n most recent files are to be compressed.

However, I am having trouble with the multiple word files. I need a way to wrap them in quote marks so the tar command knows wich is each file.

Here is my script so far:

#!/bin/bash

if [ ! -d ~/backup ]; then
    mkdir ~/backup
fi

cd ~/folder
for i in *; do
    if [ -d "$i" ]; then
        original=`pwd`
        cd $i
        echo tar zcf ~/backup/"$i".tar.gz "`ls -t | head -10`"
        cd $original
    fi
done
echo "Backup copied in $HOME/backup/"
exit 0 

Upvotes: 0

Views: 1889

Answers (2)

Dale_Reagan
Dale_Reagan

Reputation: 2061

Several workarounds if you want to stick to one-liners - simplest is probably to use 'tr' and introduce wildcard for spaces:

echo tar zcf ~/backup/"$i".tar.gz "ls -t | head -10| tr ' ' '?'"

-rw-rw-r-- 1 dale dale 35 Apr  6 09:11 test 1_dummy.txt
-rw-rw-r-- 1 dale dale 35 Apr  6 09:11 test 2_dummy.txt
-rw-rw-r-- 1 dale dale 35 Apr  6 09:11 test 3_dummy.txt
-rw-rw-r-- 1 dale dale 35 Apr  6 09:11 test 4_dummy.txt
-rw-rw-r-- 1 dale dale 35 Apr  6 09:11 test 5_dummy.txt
-rw-rw-r-- 1 dale dale 35 Apr  6 09:11 test 6_dummy.txt
-rw-rw-r-- 1 dale dale 35 Apr  6 09:11 test 7_dummy.txt
-rw-rw-r-- 1 dale dale 35 Apr  6 09:11 test 8_dummy.txt
-rw-rw-r-- 1 dale dale 35 Apr  6 09:11 test 9_dummy.txt
-rw-rw-r-- 1 dale dale 35 Apr  6 09:11 test 10_dummy.txt
-rw-rw-r-- 1 dale dale 35 Apr  6 09:11 test 11_dummy.txt  

$ tar cvf TEST.tar $(ls -t | head -5 | tr ' ' '?')
test 11_dummy.txt
test 10_dummy.txt
test 9_dummy.txt
test 8_dummy.txt
test 7_dummy.txt

Another option might be to redirect to a file and then use '-T':

ls -t | head > /tmp/10tarfiles.txt 
echo tar zcf ~/backup/"$i".tar.gz -T /tmp/10tarfiles.txt"
rm /tmp/10tarfiles.txt

Upvotes: 1

Idriss Neumann
Idriss Neumann

Reputation: 3838

if [ ! -d ~/backup ]; then
    mkdir ~/backup
fi

You can simplify by this :

[[ ! -d ~/backup ]] && mkdir ~/backup 

Now to answer your question :

$ ls -t|head -10
file with spaces
file
test.txt
test
test.sh
$ lstFiles=""; while read; do lstFiles="$lstFiles \"$REPLY\""; done <<< "$(ls -t|head -10)"
$ echo $lstFiles
"file with spaces" "file" "test.txt" "test" "test.sh"

See how to read a command output or file content with a loop in Bash to read more details.

Upvotes: 1

Related Questions