下面是基於您澄清的修改後的腳本。我用tar
檔案,與gzip
壓縮,在多個文件存儲在一個單一的存檔(不能存儲單獨使用gzip
多個文件)。此代碼只是表面測試 - 它可能有一個或兩個錯誤,你應該添加更多的代碼等檢查命令的成功,如果你在憤怒中使用它。但它應該讓你在那裏的大部分。
#!/bin/bash
oldfile=$1
newfile=$2
month=`date +%B`
year=`date +%Y`
prefix="frozenskys"
archivefile=$prefix.$month.$year.tar
# Check for existence of a compressed archive matching the naming convention
if [ -e $archivefile.gz ]
then
echo "Archive file $archivefile already exists..."
echo "Adding file '$oldfile' to existing tar archive..."
# Uncompress the archive, because you can't add a file to a
# compressed archive
gunzip $archivefile.gz
# Add the file to the archive
tar --append --file=$archivefile $oldfile
# Recompress the archive
gzip $archivefile
# No existing archive - create a new one and add the file
else
echo "Creating new archive file '$archivefile'..."
tar --create --file=$archivefile $oldfile
gzip $archivefile
fi
# Update the files outside the archive
mv $newfile $oldfile
保存爲script.sh
,然後使其可執行:
chmod +x script.sh
然後像這樣運行:
./script.sh oldfile newfile
像``frozenskys.September.2009.tar.gz , will be created, and
newfile will replace
oldfile . You can call this script with
exec`來自另一個腳本,如果你想。只要把這行寫在你的第二個腳本中:
exec ./script.sh $1 $2
好了,但因爲要存儲多個文件作爲一個壓縮文件,你現在還需要指定存檔文件名作爲額外的參數,因爲它可以不再從舊文件中確定(您可以將舊文件添加到任何現有的存檔中,或者您可能想要創建一個新文件)。你能解決你想如何在你的工作流程中工作嗎? – 2009-09-02 15:59:30
問題已更新:文件名應由腳本中的前綴常量以及當前的月份和年份創建,例如fileprefix.month.year.tar.gz – Frozenskys 2009-09-02 16:13:04
我知道我可以使用類似於PREFIX =「fileprefix」; FILENAME = $(日期+「$ PREFIX。%B.%Y.gz」)的格式來格式化文件名,但怎麼做我檢查它是否存在,如果它添加更多文件? – Frozenskys 2009-09-02 16:39:46