如何在首次安装软件包和升级期间运行脚本?

我最近开始打包我的一些软件并在Launchpad上发布。 安装和删除工作正常,但将包从一个版本升级到下一个版本是有问题的。

问题是有些脚本只需要在第一次安装包时运行。 这些脚本填充数据库,创建用户等。它们当前在package.postinst configure)部分中调用。 然而,这导致它们在升级期间被调用以及在图中示出 。

有没有办法在.deb包中包含维护者脚本,该包只在第一次安装包时执行,而不是在升级期间执行? 或者在.deb包中包含一些初始设置脚本的优雅方法是什么?

使用debian/preinst文件,您可以在安装时执行操作,但不能升级。

 #!/bin/sh set -e case "$1" in install) # do some magic ;; upgrade|abort-upgrade) ;; *) echo "postinst called with unknown argument \`$1'" >&2 exit 0 ;; esac #DEBHELPER# exit 0 

虽然顾名思义,这是在安装软件包之前运行的。 所以你可能无法在这里做你需要的。 如果用户已经创建,大多数软件包只需在postinst的configure阶段进行测试。 这是colord

 $ cat /var/lib/dpkg/info/colord.postinst #!/bin/sh set -e case "$1" in configure) # create colord group if it isn't already there if ! getent group colord >/dev/null; then addgroup --quiet --system colord fi # create the scanner group if it isn't already there if ! getent group scanner >/dev/null; then addgroup --quiet --system scanner fi # create colord user if it isn't already there if ! getent passwd colord >/dev/null; then adduser --system --ingroup colord --home /var/lib/colord colord \ --gecos "colord colour management daemon" # Add colord user to scanner group adduser --quiet colord scanner fi # ensure /var/lib/colord has appropriate permissions chown -R colord:colord /var/lib/colord ;; esac exit 0 

查看Debian wiki中关于如何调用维护者脚本的图表: Debian维护者脚本流程图

如果您按下左侧(“一切顺利”路径),您将看到使用最近配置的版本调用postinst脚本。 这使您有机会区分升级和全新安装 – 在升级的情况下,您的postinst将被称为

 postinst configure 1.23-0ubuntu1 

其中1.23-0ubuntu1是以前安装的软件包版本,而对于全新安装,它将被称为

 postinst configure 

这也允许您在从特定版本升级时需要执行操作时处理这种情况 – 您可以检查该版本的postinst

这样可以轻松检查脚本是在“安装”还是“升级”上完成的。 如果$ 2为null,那么它就是一个安装。 所以:

 if [ -z "$2" ]; then do install stuff else do upgrade stuff fi 

您可以将debian / preinst脚本与postinst结合使用。

在preinst脚本中,检查pkg肯定安装的文件。 如果它存在,不执行任何操作(因为您的软件包以前已安装),否则,请执行安装步骤。

如果您的安装步骤要求安装了您的pkg(在这种情况下上述操作不起作用,因为preinst在安装之前运行),那么您的preinst脚本可以编写一个文件,例如:/ tmp / setupmypkg。 您的postinst脚本可以简单地测试该文件是否存在,如果是,则执行以下两项操作:

  • 您的初始设置步骤
  • 删除/ tmp / setupmypkg文件

我不这么认为,但您可以轻松修改preinst / postinst脚本以检查是否首次安装软件包并采取标准操作。

可能是这样的,

在preinst。

 if not is_package_istalled(): export MY_PACKAGE_FIRST_INSTALL 

在postinst中,

 if MY_PACKAGE_FIRST_INSTALL: Do First Install Setup 

编辑

嗯,可能你可以直接在postinst中检查所有这些,因为我认为dpkg不会在执行postinst之前设置包的状态,但我不确定。 所以上面可能会来,

在postinst中,

 if not is_package_istalled(): Do First Install Setup 

在哪里,is_package_installed可以帮助您检测安装状态。 可能是’dpkg –status packagename’

要么

为什么不只是简单地检查您想要进行的更改是否已经存在,只有在它们不存在时才进行。

我发现在你的“postinst configure”脚本中测试2美元如果你之前已经安装过一次,然后卸载它(但没有清除),则无法正常运行,然后尝试重新安装。 在这种情况下,postinst脚本仍会获得“postinst configure”步骤的版本参数。

但是,如果您之前已经安装了该软件包,则删除并清除它,然后重新安装,“postinst configure”脚本将不会获得$ 2中的版本参数