【问题标题】:Shell script to backup filtered directories用于备份过滤目录的 Shell 脚本
【发布时间】:2020-01-31 23:57:13
【问题描述】:

我有几个目录要备份到带有 shell 脚本的 zip 文件。目录树如下所示:

testing
     |_ source
     |     |_ fiction_01
     |     |_ fiction_02
     |     |_ ...
     |     |_ images
     |
     |_ destination

我只想压缩以相同模式开头的目录,例如f*。对images 不感兴趣。生成的 zip 应保存到 destination。从here,我知道如何过滤名称以f 开头的所有目录。这是我的代码:

#!/bin/bash

# source and destination directories passed as 1st and 2nd parameters respectively
 SRCDIR=$1
 DESTDIR=$2

# children directories are those matching f*
 CHLDIR=$(find "$SRCDIR" -type d -name "f*") 

# name with timestamp for the .zip 
 BKPNAME=backup-$(date +%-Y%-m%-d)-$(date +%-T).zip

# actual zipping
 zip -r $DESTDIR$BKPNAME $SRCDIR$CHLDIR

脚本名为backup.sh,位于destination。这是我运行后得到的:

jm@lenovo410:~/Documents/testing/destination$ bash backup.sh ../source/ ./
  adding: ../source/../source/fiction_02/ (stored 0%)
  adding: ../source/../source/fiction_02/another.txt (stored 0%)
  adding: ../source/fiction_01/ (stored 0%)
  adding: ../source/fiction_01/list.txt (stored 0%)

压缩文件在destination 目录中创建。尽管似乎 fiction_01fiction_02(及其内容)都已添加,但当我在 zip 中检查时,只有目录 fiction_01

问题:如何压缩所有名称符合条件f*的文件夹?

【问题讨论】:

    标签: bash shell


    【解决方案1】:

    find 返回的路径名已经以$SRCDIR 开头,运行zip 时不需要连接它。您正在尝试将 /testing/source/testing/source/fiction_01 添加到 zip 文件中。

    zip -r $DESTDIR$BKPNAME $CHLDIR
    

    在调试 shell 脚本时,最好的工具之一是将 set -x 放在开头。然后,您将看到所有已执行命令的跟踪,并扩展了变量。然后你会看到这些不正确的路径名。

    【讨论】:

    • 也感谢set -x 的建议!我是新手。
    猜你喜欢
    • 1970-01-01
    • 2010-10-12
    • 2015-10-03
    • 1970-01-01
    • 2017-11-06
    • 2013-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多