Bash:维护一组文件及其等效的gzip

时间:2012-05-10 03:45:34

标签: bash synchronization directory compression gzip

我有一个目录树,其中有一些文件和一些子目录。

/
/file1.txt
/file2.png
/dir1
    /subfile1.gif

目标是创建一个脚本,生成每个文件的gzip压缩版本并将其保存在每个文件旁边,并添加.gz后缀:

/
/file1.txt
/file1.txt.gz
/file2.png
/file2.png.gz
/dir1
    /subfile1.gif
    /subfile1.gif.gz

这将处理新.gz个文件的创建。

另一部分是删除:每当创建一个非gzip压缩文件时,脚本都需要在运行时删除孤立的.gz版本。

最后也是最棘手的部分是修改:每当更改一些(非gzip)文件时,重新运行脚本将根据文件时间戳({{1}更新仅更改文件的.gz版本文件与其gzip压缩版本之间的比较。

是否可以在bash中实现这样的脚本?

编辑:这样做的目的是为nginx准备好每个文件的压缩副本,以便使用gzip_static模块提供服务。它不是一个后台服务,它会在任何更改时自动压缩事物,因为nginx的gzip_static模块足够聪明,可以在没有压缩版本的情况下提供未压缩版本的内容,或者如果未压缩版本的时间戳比gzipped版本的时间戳。因此,只要服务器不忙,这个脚本就会偶尔运行。

2 个答案:

答案 0 :(得分:2)

以下是我的尝试:

#!/bin/bash
# you need to clean up .gz files when you remove things
find . -type f -perm -o=r -not -iname \*.gz | \
while read -r x
do
    if [ "$x" -nt "$x.gz" ]; then
        gzip -cn9 "$x" > "$x.gz"
        chown --reference="$x" "$x.gz"
        chmod --reference="$x" "$x.gz"
        touch --reference="$x" "$x.gz"
        if [ `stat -c %s "$x.gz"` -ge `stat -c %s "$x"` ]; then
            rm "$x.gz"
        fi
    fi
done

从这里偷走了大部分内容:https://superuser.com/questions/482787/gzip-all-files-without-deleting-them

更改包括:

  • 跳过.gz文件
  • 添加-9和-n以使文件更小
  • 删除最终变大的文件(不幸的是,这意味着每次运行脚本时都会重试这些文件。)
  • 确保压缩文件的所有者,权限和时间戳与原始
  • 匹配
  • 仅适用于所有人都可读的文件

答案 1 :(得分:1)

这样的事,也许?

#!/bin/sh

case $1 in
  *.gz )
    # If it's an orphan, remove it
    test -f "${1%.gz}" || rm "$1" ;;
    # Otherwise, will be handled when the existing parent is handled
  * )
    make -f - <<'____HERE' "$1.gz"
%.gz: %
    # Make sure you have literal tab here!
    gzip -9 <$< >$@
____HERE
    ;;
esac

如果您已经有Makefile,请务必使用文字文件而不是here文档。

find整合作为练习。如果要保存进程,可能需要接受多个目标文件并循环遍历它们。