4

I have a large iptables ruleset that I manage with my own bash script. Most of the commands in the script are simple, single-statment iptables commands. I am trying to improve the script by adding success/failure output as the script executes.

I have the script broken out into different sections. One example would be the FORWARD chain section, where all the rules are applied to the FORWARD chain. At the beginning of the section, I output that the script has started applying the FORWARD rules, and at the end, I want to output whether or not all the rules were applied successfully, or if any of them didn't work. Here is the basic idea:

#Start FORWARD section
echo -ne "Applying FORWARD rules..."

#rule 1
/sbin/iptables -A FOWRARD...

#rule 2
/sbin/iptables -A FORWARD...

echo -ne "\t\t\t[OK]\n"

What I'm wanting to do is catch any output or errors that may result from each iptables command and store them in an array or something. Then at the end of the block, use an if statement to evaluate the array to see if there were any errors. If not, output the [OK] status, if there were, output the [FAILED] status and display the related error.

Is there a way I can do this for the entire block of rules without wrapping each iptables rule in an if [ $? != 0 ] expression?

1
  • 1
    write a function that execute for you a given command. Then use it like you would whit time, sudo, watch or strace to name some. Commented Jul 19, 2011 at 18:48

1 Answer 1

2

What about either the set -e option (exit on first failure), or:

#rule 1
/sbin/iptables -A FORWARD ... &&

#rule 2
/sbin/iptables -A FORWARD ... &&

echo "[OK]"

Assuming each command identifies errors, you won't see the OK unless everything worked.

If you have to deal with recalcitrant processes that have non-zero but successful exit statuses, then you embed such commands in a sub-shell that deals with the issue:

#rule 1
/sbin/iptables -A FORWARD ... &&

#rule 2
/sbin/iptables -A FORWARD ... &&

# Unusual process - finagle-it returns status 17 on success
(
/usr/local/sbin/finagle-it ...
if [ $? = 17 ]; then exit 0; else exit 1; fi
) &&

echo "[OK]"

Note that set -e would have to be cancelled when finagle-it is run - inside the sub-shell.

Sign up to request clarification or add additional context in comments.

1 Comment

The last subshell can be simplified: ( /usr/local/sbin/finagle-it ...; test $? = 17; ) (or, [ $? = 17 ], if preferred)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.