bash脚本存档文件,然后将复制新的
需要一些帮助,这是我的shell脚本技能是略小于L337 :(bash脚本存档文件,然后将复制新的
我需要给gzip几个文件,然后从另一顶复制较新的位置我需要能够从其他脚本调用此脚本以下列方式
exec script.sh $oldfile $newfile
任何人都可以点我在正确的方向
编辑:?要添加更多的细节:
该脚本将用于上传到一个文件夹中的一些文件,每月更新,旧文档需要归档到一个压缩文件和新的文件,这些文件可以有不同的名称,复制旧的顶部。该脚本需要通过另一个脚本的文档大小来调用文档。此脚本的基本流程应该是 -
- 脚本文件应该创建一个新的gzip 存档使用特定名称(从脚本前缀常数和当前月份和年份如prefix.september.2009创建.tar.gz)仅当它不存在 时,否则添加到现有的。
- 旧文件复制到归档。
- 取代旧文件与新的。
由于提前,
理查德
编辑:加在存档文件名
下面是基于您澄清的修改后的脚本。我用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
这差不多:) - 但我需要能够继续添加更多的文件到档案。我已经更新了这个问题,以便更好地解释我想要做的事情的流程。 – Frozenskys 2009-09-02 15:46:52
我已更新问题以添加更多详细信息。 – Frozenskys 2009-09-02 16:41:04
你是我的英雄,这很完美! – Frozenskys 2009-09-02 21:49:10
一个好的REFFERENCE任何的bash脚本是Advanced Bash-Scripting Guide模式的细节。
本指南介绍了每一件事情的bash脚本。
的基本方法我会采取的是:
Move the files you want to zip to a directory your create.
(commands mv and mkdir)
zip the directory. (command gzip, I assume)
Copy the new files to the desired location (command cp)
以我的经验的bash脚本主要是了解如何使用这些命令很好,如果你可以在命令行中运行它,你可以在你的脚本运行。
可能有用的另一个命令是
pwd - this returns the current directory
并且不要忘记错误条件,cp,mv,gzip等都可能失败,你编写的任何脚本应该尽可能健壮(好习惯),在试图操作它们之前检查$ oldfile和$ newfile是否存在。你写的命令成功了,Perl有一个很好的方法来做到这一点:“some_command ||死了“some_command失败”,但我们也可以在bash中做到这一点。 – Tim 2009-09-02 15:54:33
好点 - 但我需要弄清楚如何让脚本工作,然后才能添加错误处理:) – Frozenskys 2009-09-02 16:15:04
为什么你不使用版本控制?这很容易;只是检查出来,并压缩。
(道歉,如果这不是一个选项)
好主意,这就是我用于我的代码更新 - 使用优秀的beanstalkapp服务,但这不是这些文档的选项。 – Frozenskys 2009-09-02 16:44:36
好了,但因为要存储多个文件作为一个压缩文件,你现在还需要指定存档文件名作为额外的参数,因为它可以不再从旧文件中确定(您可以将旧文件添加到任何现有的存档中,或者您可能想要创建一个新文件)。你能解决你想如何在你的工作流程中工作吗? – 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