压缩单个文件而不是整个目录

时间:2011-11-11 04:29:02

标签: tar

大家好我已经花了好几个小时让我的脚本工作,问题是它不是压缩单个文件,而是压缩整个目录结构。

    #!/bin/sh

# Where to backup to.
mkdir -p /home/knoppix/backups --verbose
dest="/home/knoppix/backups"

# What to backup.
cat /etc/passwd >> /home/knoppix/backups/dbusers.txt
backupdb="/home/knoppix/backups/dbusers.txt"

# Create archive filename.
archive_file="DB$(date +%d%b%Y_%H%M).tgz"

# Print start status message.
echo "Backing up $backupdb to $dest/$archive_file"
date
echo

# Backup the files using tar.
tar czf $dest/$archive_file $backupdb

2 个答案:

答案 0 :(得分:3)

尝试使用tar -C进入目录:

#!/bin/sh

# Where to backup to.
mkdir -p /home/knoppix/backups --verbose
dest="/home/knoppix/backups"

# What to backup.
cat /etc/passwd >> /home/knoppix/backups/dbusers.txt
backupdir="/home/knoppix/backups"
backupfile="dbusers.txt"

# Create archive filename.
archive_file="DB$(date +%d%b%Y_%H%M).tgz"

# Print start status message.
echo "Backing up $backupdb to $dest/$archive_file"
date
echo

# Backup the files using tar.
tar czf $dest/$archive_file -C $backupdir $backupfile

GNU tar还提供了--transform选项,可用于调整存档创建或提取的名称。改变原始脚本的另一种方法是执行以下操作:

#!/bin/sh

# Where to backup to.
mkdir -p /home/knoppix/backups --verbose
dest="/home/knoppix/backups"

# What to backup.
cat /etc/passwd >> /home/knoppix/backups/dbusers.txt
backupdir="/home/knoppix/backups"
backupfile="dbusers.txt"

# Create archive filename.
archive_base_name="DB$(date +%d%b%Y_%H%M)"
archive_file="$archive_base_name.tgz"

# Print start status message.
echo "Backing up $backupdb to $dest/$archive_file"
date
echo

# Backup the files using tar.
tar --transform="s#^$base#$archive_base_name#" czPf $dest/$archive_file $backupdb

--transform的参数表示将一个文本字符替换为另一个文本,例如s#old#new#old部分实际上是一个称为正则表达式的模式,而^将使正则表达式仅在一行的开头匹配。而P(在czPf中)告诉tar不要从路径的开头删除'/'。因此,在此示例中,将使用以下内容创建tar:

DB11Nov2011_0555/dbusers.txt

如果您的现有存档包含名为“dbusers.txt”的文件,则可以使用--transform将其解压缩到其他名称或目录:

tar --transform="s#dbusers#original#" xzf example.tgz # creates original.txt
tar --transform="s#^#output/#" xzf example.tgz        # creates output/dbusers.txt

尝试将v添加到tar选项(czPvf),以使其显示添加或提取文件的名称。使用--transform时,使用--show-transformed-names也可能会有所帮助,以便v标记显示替换结果而不是原始名称。

最后,要获得更多疑难解答帮助,请尝试在脚本顶部(或set -x命令之前)添加tar。它将导致shell在执行命令之前打印命令。有用的部分是,它将显示在评估变量和通配符之后使用的

您甚至可以在命令行上尝试此操作。如果退回则使用set +x转:

$ set -x
$ archive_file="DB$(date +%d%b%Y_%H%M).tgz"
++ date +%d%b%Y_%H%M
+ archive_file=DB11Nov2011_0605.tgz
$ echo $archive_file
+ echo DB11Nov2011_0605.tgz
DB11Nov2011_0605.tgz
$ set +x
+ set +x
$ echo $archive_file
DB11Nov2011_0605.tgz

答案 1 :(得分:1)

怎么样:

# Backup the files using tar.
(cd /home/knoppix/backups/; tar czf $dest/$archive_file dbusers.txt)