如何在Bash脚本中编写幂等文件更新?

时间:2013-12-01 07:48:36

标签: bash

我正在编写一个将更新配置文件的bash脚本。现在它只是将文件移动到位:

if [ ! -e /path/to/file.conf ]; then
  mv file.conf /path/to/file.conf
fi

但是,现在我意识到我可能希望将来对该文件进行更改,因此如果文件已经存在,那么简单的移动将无法工作。如何编写此文件,以便以允许我多次执行相同脚本(幂等)的方式使用正确的内容更新文件?

1 个答案:

答案 0 :(得分:1)

考虑:

if cmp -s file.conf /path/to/file.conf
then : OK - identical
else mv /path/to/file.conf /path/to/file.conf.$(date +%Y%m%d.%H%M%S)
     mv file.conf /path/to/file.conf
fi

保留配置文件的先前版本的过时副本,这使得在出现问题时更容易回滚。还有其他的,可以说是更好的方法来处理这个问题。问题在于它将配置文件与替换时的日期保持一致,而不是在创建时。

所以,另一种选择是:

if cmp -s file.conf /path/to/file.conf
then : OK - identical
else now=$(date +%Y%m%d.%H%M%S)
     mv file.conf /path/to/file.conf.$now
     rm /path/to/file.conf
     ln -s /path/to/file.conf.$now /path/to/file.conf
fi

这会留下一个名为/path/to/file.conf的符号链接,它指向配置文件的日期版本 - 在创建时。您可以随时删除符号链接并添加其他版本,或者将其更改为指向旧版本而不必删除较新版本等。

相关问题