2

需要一些帮助,因为我的 shell 脚本技能略低于 l337 :(

我需要 gzip 几个文件,然后从另一个位置复制较新的文件。我需要能够以以下方式从其他脚本中调用此脚本。

exec script.sh $oldfile $newfile

谁能指出我正确的方向?

编辑:添加更多细节:

此脚本将用于每月更新一些上传到文件夹的文档,旧文档需要归档到一个压缩文件中,新文档可能有不同的名称,复制到旧文档的顶部。需要从另一个脚本逐个文档案例调用该脚本。此脚本的基本流程应该是 -

  1. 脚本文件应该创建一个具有指定名称的新 gzip 存档(从脚本中的前缀常量和当前月份和年份创建,例如 prefix.september.2009.tar.gz),除非它不存在,否则添加到现有的。
  2. 将旧文件复制到存档中。
  3. 用新文件替换旧文件。

在此先感谢,
理查德

编辑:在存档文件名上添加了模式详细信息

4

3 回答 3

2

任何 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
于 2009-09-02T15:01:51.190 回答
2

这是根据您的说明修改后的脚本。我已经使用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将被创建,newfile并将替换oldfile. 如果需要,您也可以exec从另一个脚本调用此脚本。只需将此行放入您的第二个脚本中:

exec ./script.sh $1 $2
于 2009-09-02T15:21:21.263 回答
0

为什么不使用版本控制?这要容易得多;只需检查并压缩。

(抱歉,如果它不是一个选项)

于 2009-09-02T16:40:52.663 回答