kd.maxi
kd.maxi

Reputation: 70

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.

Upvotes: 1

Views: 17031

Answers (2)

Gordon Davisson
Gordon Davisson

Reputation: 125918

@py9 has already answered the question, but I'd like to point something else out: when testing whether a command succeeded, it's simpler and somewhat more robust to use the command directly as the if condition, rather than using $? to check its exit status afterward. Also, rather than redirecting grep's output to /dev/null, you can use grep -q (quiet mode). Finally (as @CharlesDuffy pointed out), grep -E understands extended regular expression syntax, which doesn't include \s (that's part of PCRE -- perl-compatible regular expression -- syntax). So use something like this:

if grep -q -E '^[[:space:]]*PermitEmptyPasswords[[:space:]]+no[[:space:]]*' /etc/ssh/sshd_config; then
    echo "[ OK ] PermitEmptyPasswords is properly configured"
else
    echo "[ ERROR ] PermitEmptyPasswords is not properly configured"
    ((count++))
fi

Upvotes: 3

py9
py9

Reputation: 626

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.

Upvotes: 2

Related Questions