Dan Dan - 6 months ago 13
Bash Question

Bash else/if capture exit status

Please help me fix the 'elseif' line in the following script so that it can capture the exit status of zero and proceed without error, since I do not know the correct syntax to construct this.

I need to capture the zero from the following command, but within the parentheses in the script.

softwareupdate -l 2>&1 | grep restart


My script:

#!/bin/bash
PATH=/bin:/usr/bin:/sbin:/usr/sbin export PATH
SWLOG=/var/log/swupdate.log

softwareupdate -l 2>&1 | grep "No new software available."

if [ $? -eq 0 ]

then
echo "No new software was deemed to be available"

elif [ $(softwareupdate -l 2>&1 | grep restart & $? = 0) ]

then
echo "RESTART will be needed"

else
echo "Updates needed, but not restart"

fi


Thank you in advance for your suggestions and ideas!

Dan

Answer

You can use grep -q and avoid using $?:

#!/bin/bash
PATH=/bin:/usr/bin:/sbin:/usr/sbin export PATH 
SWLOG=/var/log/swupdate.log

if softwareupdate -l 2>&1 | grep -q "No new software available."
then
  echo "No new software was deemed to be available"    
elif softwareupdate -l 2>&1 | grep -q restart    
then
  echo "RESTART will be needed"    
else
  echo "Updates needed, but not restart"    
fi