2015-09-06 86 views
0

我需要刪除比參數中給定的文件更早的文件,並將它們添加到存檔中並保存結構。刪除存檔文件

文件中列出

[email protected]:~/test.d$ ls -l 
total 20 
-rw-rw-r-- 1 oracle oracle 0 Sep 6 07:06 aug 
-rw-rw-r-- 1 oracle oracle 0 Feb 10 2015 feb 
-rw-rw-r-- 1 oracle oracle 0 Sep 6 07:06 june 
-rw-rw-r-- 1 oracle oracle 0 Mar 3 2015 march 
-rw-rw-r-- 1 oracle oracle 0 Sep 6 07:06 may 
drwxrwxr-x 3 oracle oracle 4096 Sep 6 08:00 rem-old-res 
-rwxrw-r-- 1 oracle oracle 469 Sep 6 08:00 rem-old.sh 
-rwxrw-r-- 1 oracle oracle 467 Sep 6 08:00 rem-old.sh~ 
-rw-rw-r-- 1 oracle oracle 85 Sep 6 08:00 roll-back.sh 
drwxrwxr-x 2 oracle oracle 4096 Sep 6 07:35 some.d 

[email protected]:~/test.d/some.d$ ls -l 
total 0 
-rw-rw-r-- 1 oracle oracle 0 Sep 6 07:06 test1 
-rw-rw-r-- 1 oracle oracle 0 Sep 6 07:06 test2 
-rw-rw-r-- 1 oracle oracle 0 Jan 4 2015 test3 

run-on.sh

#!/bin/bash 

dirname=$2 
date=$1 
now=`date +%Y-%m-%d` 
here=`pwd` 

mkdir $HOME/rem-old-res 
touch temp-file -d $date 

cp * -R $HOME/rem-old-res 
cp -R $HOME/rem-old-res/ $here/rem-old-res 

for file in `find rem-old-res -type f -newer temp-file` 
do 
    rm $file 
done 

tar czf rem-old-res.tar.gz rem-old-res 

echo "#!/bin/bash" > $here/roll-back.sh 
echo "tar xvzf $HOME/rem-old-res.tar.gz $here/rem-old-res" >> $here/roll-back.sh 


rm -rf $HOME/rem-old-res 
rm $here/temp-file 

腳本調用,如:

./run-on.sh 20150501 

二月,三月和TEST3文件是有被腳本刪除,但是你不要。我無法得到爲什麼循環無法正常工作。

+0

後的腳本是如何被調用(與參數) – amdixon

+0

@cdarke對不起,我整夜工作,累了一點。這就是我所說的腳本./run-on.sh 20150501.根據我在結果中的結構,我期望得到tar.gz-archive 3個文件:feb,march,some.d/test3。但是現在我只有名爲rem-old-res的目錄得到空檔案。 – kozlone

+0

,run-on.sh不在test.d目錄中 – amdixon

回答

0

這裏是我的問題的解決方案:

#!/bin/bash 

# example of usage ./rem-old.sh 20150501 . 
# The first parametr is a date in the format YYMMDD and the second is a path to the particular direcoty 

dirname=$2 
date=$1 
now=`date +%Y-%m-%d` 
here=`pwd` 

touch temp-file -d $date 

for file in `find -type f ! -newer temp-file` 
do 
    if [[ $file != "./temp-file" ]] 
    then 
     tar --append --file=rem-old-res.tar $file 
     rm $file 
    fi 
done 

gzip rem-old-res.tar 

# roll-back.sh is a script to cancel the changes 
echo "#!/bin/bash" > $here/roll-back.sh 
echo "gzip -d rem-old-res.tar.gz" >> $here/roll-back.sh 
echo "tar -xvf rem-old-res.tar" >> $here/roll-back.sh 
echo "rm rem-old-res.tar" >> $here/roll-back.sh 
chmod u+x roll-back.sh 

rm $here/temp-file 
1

我認爲你的方法很不錯,但是你沒有閱讀好手冊。

tar有一個參數用於從磁盤中刪除添加到存檔的文件。

touch使用-t參數設置文件時間。

此外,你應該小心在bash使用變量,請參閱pitfalls總是用引號

#!/bin/bash 

dirname=$2 
date=$1 
now=`date +%Y%m%d%H%M` 
here=`pwd` 

touch -t "$date" temp-file 
find "$here" -newer temp-file tarfiles 
tar -czf rem-old-res.tar.gz -T tarfiles --remove-files 

echo "#!/bin/bash" > $here/roll-back.sh 
echo "tar xvzf $HOME/rem-old-res.tar.gz $here/rem-old-res" >> $here/roll-back.sh 

rm $here/temp-file 
rm $here/tarfiles