Bash scripting: error detection from statement block

I have a large set of iptables rules that I control with my own bash script. Most of the commands in the script are simple iptables with the same status. I am trying to improve the script by adding a success / failure result when the script is executed.

I have a script divided into different sections. One example is the FORWARD section, where all rules apply to the FORWARD chain. At the beginning of the section, I deduced that the script started to apply FORWARD rules, and at the end I want to indicate whether all the rules were applied successfully or if any of them did not 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 want to do is to catch any output or errors that may occur as a result of each iptables command and store them in an array or something like that. Then at the end of the block use the if statement to evaluate the array to see if there were any errors. If not, display the status [OK]; if they are, display the status [FAILED] and display the corresponding error.

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

+4
source share
1 answer

Regarding 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 will not see OK if everything did not work.

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

 #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 will need to be canceled when finagle-it is launched - inside the sub-shell.

+2
source

All Articles