0

I am getting the output of the first if script but unable to get the output of the second part of the if statement in the below script:

#!/bin/ksh

err_abc=`grep -r "XYZ" /home |wc -l`
err_AB=`grep -r "XYZ" /home` > /dev/null 2>&1
err_ERR=`grep -r "ERROR" /home |wc -l`
err_eRR=`grep -r "ERROR" /home` > /dev/null 2>&1

if [ $err_abc -gt 0 ]
then
    echo "$err_AB"
else
    echo "No errors found"

    if [ $err_ERR -gt 0 ]
    then
        echo "$err_eRR"
    else
        echo " \n No err files found"
        exit 0
    fi
fi
  • why nested ifs ? – RomanPerekhrest Oct 13 '17 at 16:01
  • you mean grep -r -c "XYZ" /home ? – User123 Oct 13 '17 at 16:05
  • 1
    @User123 I think he means why are both of your fi statements at the end. One of them should be before your second if. – Jesse_b Oct 13 '17 at 16:06
3

Are you sure the code is doing what you think it's doing? Let's indent it so that we can more easily see the logic:

if [ $err_abc -gt 0 ]; then
    echo "$err_AB"
else
    echo "No errors found"
    if [ $err_ERR -gt 0 ]; then
        echo "$err_eRR"
    else
        echo " \n No err files found"
        exit 0
    fi
fi

Your second if block is only executing if and only if the first block's test is falsy. If you want both tests to be run in all cases, this needs to be rewritten:

if [ $err_abc -gt 0 ]; then
    echo "$err_AB"
else
    echo "No errors found"
fi
if [ $err_ERR -gt 0 ]; then
    echo "$err_eRR"
else
    echo " \n No err files found"
    exit 0
fi

Also, the exit 0 you have in your final if statement's else clause is only executed if any only if the second test is falsy. If this is not your intent, that statement should be moved appropriately.

  • No, I want to check the both conditions ...first as well the second one...second if statement is not dependent on first one. – User123 Oct 13 '17 at 16:11
  • 1
    It is as written. See my revised answer. – DopeGhoti Oct 13 '17 at 16:13
0

You're doing a lot of extra work to set the variables: you're recursively grepping 4 separate times. You only need to do that once:

all_errs=$(grep -r -E "XYZ|ERROR" /home 2>/dev/null)

Then the other information can be retrieved from that variable

err_AB=$(grep "XYZ" <<< "$all_errs)
err_abc=$(wc -l <<< "$err_AB")

err_eRR=$(grep "ERROR" <<< "$all_errs")
err_ERR=$(wc -l <<<"$err_eRR")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.