Even if one of these commands fail, my script should exit with non-zero code i.e 16.
If all commands are successful, my script should exit with 0.
My action for this requirement :
I am collecting return codes of all commands into a variable and grepping for a non-zero string in that variable. If it is found I am exiting the script with 16 otherwise exit the script with 0.But , my code is not working in case the variable is having all zeros' .
In both cases grep is returning 1.
If it var contains all zeros, then my script should exit with 0.
This is my actual script:
#Command execution function
_Command()
{
_Report "BEGIN Command : $@ "
#Executing command and redirecting stderr to devnull
output=$(eval $@)
#Exit status of the command
stat=$?
echo $output
echo "++ $stat ++"
if [[ $stat -ne 0 ]] ; then
#collecting all return codes of commands into a variable
Returns=$Returns" "$stat
_Report "$@ not successful"
_Report "END"
else
Returns=$Returns" "$stat
_Log "$output"
_Report "END"
fi
}
#List of commands to be run for unix swap space problem
_Report "## memory size used by each of the running processes ##"
_Command 'ps -eo vsz,pid,args | sort -n'
_Report "## memory that is locked but not used ##"
_Command 'ipcs -ma | grep -w -E "0|NATTCH" '
_Report "## Check for virtual memory statistics ##"
_Command "vmstat"
_Command "ps -ef | grep micro"
#Search for nonzero code in all the exitcodes of commands
echo $Returns
echo $Returns | grep -qv 0
#If one of the commands fail, autocheck script will return 16
[ $? = 1 ] && exit $Error || exit $Success
Please help or suggest any alternatives...
Many thanks in advance,
thanks ahamed and rod... both solutions work.. however i got another idea just now...
I am not collecting succesful commands, instead i am collecting only non-zero codes...
so, i f all commands are succesful, $var contains " " or $var contains "127 ".
So, I wrote this to handle, it is working not efficient though, am i right:
my $var contains either var=" 127 255" or var=" "..
#If one of the commands fail, autocheck script will return 16
if $var 2>/dev/null ; then
exit $Success
else
exit $Error
fi
Alternatively, he could have grepped for a non-zero digit. Although, if each individual exit status is not required, radoulov's suggestion is probably best. And since it seems that the command sequence is known at "compile" time, there's really no need for eval.
Regards,
Alister
---------- Post updated at 11:05 AM ---------- Previous update was at 11:02 AM ----------