0

I would want the bash scripting to run the following command

iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 10000

if there is no output of it found using

iptables -t nat --list

How can I use the If-Else to look for the output. Can i use 'cat' ?

2 Answers 2

2

Use $() to capture the output of a command and -z to determine if it is empty:

output=$(iptables -t nat --list)
if [ -z $output ] # returns true if the length of $output is 0
then
    output=$(iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 10000)
fi
Sign up to request clarification or add additional context in comments.

2 Comments

I don't think they just want iptables -t nat --list to be empty, it pretty much never will be since it prints headers if nothing else. I think they want to check if that routing rule is already there, which would be the "of it" in their expression--though of course I can't be sure that's what they mean
@EricRenouf I didn't know that, thanks for the heads-up. In that case I'll upvote your answer.
2

You could use grep with the iptables list, depending on how you're trying to match it.

if iptables -t nat --list PREROUTING | grep -- '--destintation-port 80' | grep -q -- '--to-port 10000'
    iptables -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port 10000
fi

This will look if there is a PREROUTING entry that concerns both --destination-port 80 and --to-port 10000. If the output string is more predictable you could use a single grep for it, but I don't know iptables well enough to offer that as part of the solution

Comments

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.