Search code examples
bashscriptingrhelif-case

Bash scripting - if cases $? > 0


Sorry for possible spam, I'm finishing RHEL Security Hardening/Auditing script, where I want an overall result in the end. For example,

# PermitEmptyPasswords
grep -E '^\s*PermitEmptyPasswords\s+no\s*' /etc/ssh/sshd_config &> /dev/null
if [ $? = 0 ];
then echo "[ OK ] PermitEmptyPasswords is properly configured";
else echo "[ ERROR ] PermitEmptyPasswords is not properly configured";
fi

Now, my idea for overall result (Safe/Not safe) is to make sum of all these if $? cases, if all cases give sum of 0, it will echo "This system is properly configured by hardening policy", else echo "This system has errors" + reprint all errors where $? is > 0.

How to get this work? I'm new at scripting, so any help will be appreciable. Thanks in advance.


Solution

  • What you can do is:

    create an empty variable and give it a value of 0

    count=0
    

    Increment it by 1 every time you have an exit status bigger than 0. Example:

    if [[ $? -gt 0 ]]; then ((count++)); fi
    

    To print it all out at the end, you can do a simple array, but I think just appending the content to a file, and then reading at the end should suffice.

    if [[ $? -gt 0 ]]; then ((count++)) && echo "whatever" >>filename; fi
    

    At the end, just cat the filename and to show to the number of errors, just echo the count variable:

    echo "Count number: $count"
    

    P.S use double opening and closing brackets if you are using bash as your shell.