Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/joomla/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Shell 用于安装包并捕获错误的Bash脚本_Shell - Fatal编程技术网

Shell 用于安装包并捕获错误的Bash脚本

Shell 用于安装包并捕获错误的Bash脚本,shell,Shell,我想通过shell脚本安装一个包,并向服务器发送一个请求,如果该包安装成功,如果安装失败,则应向服务器发送错误消息。 我想出了下面的剧本 { apt-get install <PACKAGE> && # Send Success to Server } || { # Catch Error Message Here # Send Error Message to Server } { 安装&& #发送成功到服务器 } || { #在此捕获错误消息 #

我想通过shell脚本安装一个包,并向服务器发送一个请求,如果该包安装成功,如果安装失败,则应向服务器发送错误消息。 我想出了下面的剧本

{
  apt-get install <PACKAGE> &&
  # Send Success to Server
} || {
  # Catch Error Message Here
  # Send Error Message to Server
}
{
安装&&
#发送成功到服务器
} || {
#在此捕获错误消息
#向服务器发送错误消息
}

如何捕获错误消息?

考虑将apt get包装到if语句中。它通常比使用“&&”和“| |”更容易

if apt-get install PACKAGE ; then
   # Send success
   echo "OK"
else
   # Send error
   echo "Error"
fi
如何捕捉错误消息

将输出流(stdout和stderr)保存到某处。然后将流内容发送到服务器。下面我将stderr重定向到stdout,并将两者捕获到一个变量,然后只发送变量内容

if message=$(apt-get install PACKAGE 2>&1); then
     echo success;
else
     Send_Error_Message_to_Server "$message"
fi
变量赋值保留内部执行的最后一个命令的退出状态,因此,如果您愿意,可以使用您的语法:

{ 
   message=$(apt-get install <PACKAGE> 2>&1) &&
   # Send Success to Server
} || {
   Send_Error_Message_to_Server "$message"
}
{
消息=$(apt get install 2>&1)&&
#发送成功到服务器
} || {
将错误消息发送到服务器“$Message”
}