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

Har*_*rel 7 apt bash scripts

我正在编写一个 bash 脚本来安装软件和更新 Ubuntu 12.04。我希望脚本能够检查 apt-get 错误,尤其是在 apt-get 更新期间,以便我可以包含纠正命令或退出脚本并显示消息。如何让我的 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!"
Run Code Online (Sandbox Code Playgroud)

ter*_*don 12

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

sudo apt-get install BadPackageName && 
## Rest of the script goes here, it will only run
## if the previous command was succesful
Run Code Online (Sandbox Code Playgroud)

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

sudo apt-get install BadPackageName || echo "Installation failed" && exit
Run Code Online (Sandbox Code Playgroud)

这将提供以下输出:

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
Run Code Online (Sandbox Code Playgroud)

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

  • && : 仅当上一个命令成功时才继续(退出状态为 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
Run Code Online (Sandbox Code Playgroud)

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