Dev
Dev

Reputation: 67

Bash Script to Install package and catch error

I want to install a package via shell script and send a request to server if that package was installed successfully and if failed, the error message should be sent to the server. I have comeup with the following script

{
  apt-get install <PACKAGE> &&
  # Send Success to Server
} || {
  # Catch Error Message Here
  # Send Error Message to Server
}

How I can catch the error message?

Upvotes: 0

Views: 701

Answers (2)

KamilCuk
KamilCuk

Reputation: 140990

How I can catch the error message?

Save output streams - stdout and stderr - somewhere. Then send the streams contents to your servers. Below I redirect stderr to stdout and capture both to a variable - then just send the variable content.

if message=$(apt-get install PACKAGE 2>&1); then
     echo success;
else
     Send_Error_Message_to_Server "$message"
fi

Variable assignment preserves the exit status of the last command executed inside, so you may use your syntax if you wish:

{ 
   message=$(apt-get install <PACKAGE> 2>&1) &&
   # Send Success to Server
} || {
   Send_Error_Message_to_Server "$message"
}

Upvotes: 1

dash-o
dash-o

Reputation: 14452

Consider wrapping the apt-get in an if statement. It's usually easier than to use the '&&' and '||'

if apt-get install PACKAGE ; then
   # Send success
   echo "OK"
else
   # Send error
   echo "Error"
fi

Upvotes: 0

Related Questions