如何在bash脚本中检查apt-get错误?

我正在编写一个bash脚本来安装软件并更新Ubuntu 12.04。 我希望脚本能够检查apt-get错误,特别是在apt-get update期间,这样我就可以包含更正命令或者使用消息退出脚本。 如何让我的bash脚本检查这些类型的错误?

编辑3月21日:感谢terdon提供我需要的信息! 这是我创建的脚本,其中包含检查更新的建议,并在发生错误时重新检查,然后报告。 我将把它添加到我用来定制新的Ubuntu安装的更长的脚本中。

#!/bin/bash apt-get update if [ $? != 0 ]; then echo "That update didn't work out so well. Trying some fancy stuff..." sleep 3 rm -rf /var/lib/apt/lists/* -vf apt-get update -f || echo "The errors have overwhelmed us, bro." && exit fi echo "You are all updated now, bro!" 

最简单的方法是仅在apt-get正确退出时才使脚本继续运行。 例如:

 sudo apt-get install BadPackageName && ## Rest of the script goes here, it will only run ## if the previous command was succesful 

或者,如果任何步骤失败,请退出:

 sudo apt-get install BadPackageName || echo "Installation failed" && exit 

这将给出以下输出:

 terdon@oregano ~ $ foo.sh [sudo] password for terdon: Reading package lists... Done Building dependency tree Reading state information... Done E: Unable to locate package BadPackageName Installation failed 

这是利用bash和大多数(如果不是全部)shell的基本function:

  • && :仅在前一个命令成功(退出状态为0)时继续
  • || :仅在前一个命令失败时退出(退出状态不为0)

这相当于写这样的东西:

 #!/usr/bin/env bash sudo apt-get install at ## The exit status of the last command run is ## saved automatically in the special variable $?. ## Therefore, testing if its value is 0, is testing ## whether the last command ran correctly. if [[ $? > 0 ]] then echo "The command failed, exiting." exit else echo "The command ran succesfuly, continuing with script." fi 

请注意,如果已安装软件包, apt-get将成功运行,退出状态将为0。

你可以设置停止脚本的选项,如下所示:

 set -o pipefail # trace ERR through pipes set -o errexit # same as set -e : exit the script if any statement returns a non-true return value