Home > front end >  Bash script to check iptables rules for loop with if condition
Bash script to check iptables rules for loop with if condition

Time:10-01

I saved ports in an array that I wanted to check, then I'm running a for loop to check for the port in iptables rule list. I want to echo Ports that are not in the iptables list with msg not found. Tried to add an if condition inside the loop but not working. here's the code: [Non-working ;) ]

#!/bin/bash
array=( 3306 1403 8080 443 22 )
for i in "${array[@]}"
pc=(iptables --list | grep $i | cut -d " " -f1)
do
if [ "${pc}" = "ACCEPT" ]
then 
echo "ok"
else
echo "Port not found"
fi
done

Error: array.sh: line 4: syntax error near unexpected token |' array.sh: line 4: pc=(iptables --list | grep $i | cut -d " " -f1)' array.sh: line 5: syntax error near unexpected token do' array.sh: line 5: do'

CodePudding user response:

Two syntax issues:

#!/bin/bash
array=( 3306 1403 8080 443 22 )
for i in "${array[@]}"
do
    pc=$(iptables --list | grep $i | cut -d " " -f1)
    if [ "${pc}" = "ACCEPT" ]
    then 
        echo "ok"
    else
        echo "Port not found"
    fi
done

CodePudding user response:

I am not attempting to syntax check the entire script, but there appears to me an obvious issue; you're assigning the pc evar before the do. This becomes very evident if you format your code with tabs. For example:

#!/bin/bash
array=( 3306 1403 8080 443 22 )

for i in "${array[@]}"
pc=(iptables --list | grep $i | cut -d " " -f1)
do
    if [ "${pc}" = "ACCEPT" ]
    then 
        echo "ok"
    else
        echo "Port not found"
    fi
done

From the above, you can see that pc is not being set inside the for loop. Try this instead:

#!/bin/bash
array=( 3306 1403 8080 443 22 )

for i in "${array[@]}"
do
    pc=$(iptables --list | grep $i | cut -d " " -f1)
    if [ "${pc}" = "ACCEPT" ]
    then 
        echo "ok"
    else
        echo "Port not found"
    fi
done

Edit: Also, @tink (made it 1 minute before me) noticed there's a missing $ in the assignment of the pc variable. I've updated my answer to make that clear as well. HTH

  • Related