如何使用 bash 在连续运行中创建具有相同 metadata/timestamps 的目录结构?

How to create directory structure with identical metadata/timestamps on consecutive runs using bash?

$ install -m755 -d "/tmp/usr/lib/modules/4.14.4-1-ARCH/kernel"

在创建 Linux initramfs 文件的 bash 脚本中创建多个新目录条目。为了使 file/folder 元数据在运行之间保持一致,我们的想法是将文件夹时间戳引用到内核本身,其中 touch --reference=<source_file> <new_created_directory>.

可以通过install --verbose命令检索单独要触摸的文件夹,例如:

$ install -v -m755 -d "/tmp/usr/lib/modules/4.14.4-1-ARCH/kernel"
install: creating directory '/tmp/usr'
install: creating directory '/tmp/usr/lib'
install: creating directory '/tmp/usr/lib/modules'
install: creating directory '/tmp/usr/lib/modules/4.14.4-1-ARCH'
install: creating directory '/tmp/usr/lib/modules/4.14.4-1-ARCH/kernel'

路线

  1. 将文件描述符 #1 的输出重定向到一个数组,并循环遍历该数组。也许数组甚至不是必要的,install -v -d 输出可以立即通过管道传输到 readline 类型的代码块中。
  2. 目录遍历从创建的目录一直到临时initramfs的根目录,在上面的例子中/tmp

如何在连续运行时创建具有相同元数据的目录结构?例如,必要的 touch 命令循环和参数扩展 (PE) 以匹配新创建的目录 install?


The parent bash script is writing a skeleton minimal Linux file and folder structure to a temporary location, that will finally be compressed into an initramfs structure. The goal is to be able to recreate binary identical initramfs files on consecutive script runs. By default the files are identical, but the metadata is not due to different creation/access timestamps.

目录结构准备就绪后,可以根据它创建initramfs, 将所有文件和目录的时间戳设置为一个参考点。 您可以为此使用 find 命令:

find path/to/basedir -exec touch -r "$reference_file" {} +

如果您只想触摸由 install 命令创建的文件, 比您可以创建一个可以与 find-newer 谓词一起使用的标记文件,例如:

marker=/tmp/marker
touch "$marker"
install ...

find path/to/basedir -newer "$marker" -exec touch -r "$reference_file" {} +

如果你想特别触摸 install -v -d ... 打印的文件, 所有输出行都应具有以下格式:

install: creating directory '...'

然后你可以将 install 的输出通过管道传递给逐行读取的循环, 并通过截断行的前缀直到第一个 ' 来提取路径, 并从最后一个 ':

中删除所有内容
... | while read -r line; do
    [[ $line = *'install: creating directory '* ]] || continue
    line=${line#*\'}
    line=${line%\'*}
    touch -r "$reference_file" "$line"
done