【问题标题】:How can I tar files in a directory with Bash [duplicate]如何使用 Bash 压缩目录中的文件 [重复]
【发布时间】:2017-04-24 20:39:00
【问题描述】:

我正在尝试 tar 超过 3 天的文件。我查看了现有问题creating tar file and naming by current date,但是当我运行脚本时,文件不会被修改。有人有什么建议吗?

# Tar files older than 3 days
files=($(find /this/is/my_path/ -type f -mtime +3))
tar -cvfz backup.tar.gz "${files[@]}"
if [ ! -f ${LOGFILE}.tar.gz ]; then
  Error checking
  if [ $? -ne 0 ]; then
     Process_Error $ERROR_SUM "This file had a problem $FILE!"
  fi
fi

}

【问题讨论】:

  • 尝试-cvzf 您当前正在创建一个名为z 的文件。
  • 另外,files=($(find /this/is/my_path/ -type f -mtime +3)) 不能处理名称中带有空格的文件(some file.txt 将变成两个条目,somefile.txt)。而/this/is/my_path/ * IMPORTANT *.txt 会将第一个* 替换为当前目录中的文件列表,并将*.txt 替换为文本文件列表。
  • @user7915836 顺便说一句,${LOGFILE}.tar.gz$ERROR_SUM 没有被引用也可能存在问题——shellcheck.net 会检测到。顺便说一句,考虑使用小写变量名——请参阅pubs.opengroup.org/onlinepubs/9699919799/basedefs/… 上的相关 POSIX 约定,为对 OS 和 shell 有意义的变量名指定全大写名称,并保留小写字符的名称以供应用程序使用。 (因为设置与环境变量同名的 shell 变量会覆盖后者,所以相同的约定适用于两者)。

标签: linux bash tar


【解决方案1】:
files=( )
while IFS= read -r -d '' file; do
  files+=( "$file" )
done < <(find /this/is/my_path/ -type f -mtime +3 -print0)
tar -cvzf backup.tar.gz -- "${files[@]}"
  • a comment on the question by @123 中所述,直接跟随 -f 的参数是一个文件名;在上面,它变成了z
  • array=( $(...) ) 天生不可靠:它依赖于 IFS 中字符的字符串拆分来查找文件名之间的边界。但是,路径中唯一不能出现的字符是 NUL —— NUL 不能存储在字符串(IFS 的数据类型)中。请参阅 BashPitfalls #1(目前,files=($(find . -type f)) 示例是倒数第二个)。

【讨论】:

  • 你为什么要回答然后标记为重复?
  • Cyrus pointed out the duplicate 在我回答之后。
  • 嗯,很公平,不过你一定知道它是重复的......
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-02
  • 2018-01-28
  • 2016-12-28
相关资源
最近更新 更多