我正在编写一个 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!"
答案1
最简单的方法是让脚本仅在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 的基本功能:
&&
:仅当前一个命令成功时才继续(退出状态为 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。
答案2
您可以设置选项来停止脚本,如下所示:
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