0

I'm relatively 'beginner' in the world of Linux and bash and I cannot figure this out.

Among other things I want to modify iptables if 'string' doesn't exist in there, but it doesn't seem to work. Not sure if this is because of the if statements, exit code, syntax or sudo permissions or other.

When the script is being run automatically via cron, it performs the if clause even if iptables does contain the string I'm looking for. This is verified by

  1. printing iptables in terminal both seconds before and after a scheduled run
  2. by adding an echo "this" >>/log/file.log to the if clause.

Take 1:

#!/bin/bash
iptables -L -n -v | grep 8.8.8.8
if [ $? != 0 ]; then
    command-to-perform
fi

Take 2:

#!/bin/bash
iptablesvar=$(iptables -L -v -n)
if [[ $iptablesvar != *"8.8.8.8"* ]]; then
    command-to-perform
fi

I've tried both, triggered by (sudo) crontab with the following line:

*/1 * * * * /bin/bash /home/username/path/to/script-file.sh

What baffles me, is that both the options above seems to work when entered directly into the terminal like so:

sudo iptables -L -n -v | grep 8.8.8.8
if [ $? != 0 ]; then echo "not found" ;fi
if [ $? == 0 ]; then echo "found" ;fi

var=$(sudo iptables -L -n -v)
if [[ $var != *"8.8.8.8"* ]]; then echo "n" ;fi
if [[ $var == *"8.8.8.8"* ]]; then echo "y" ;fi

What gives?

If relevant, my system is a fresh Linux Mint 19.3 Tricia

11
  • 1
    A lot useful links, stackoverflow.com/questions/14612444/… – Jetchisel Apr 15 '20 at 7:54
  • 1
    What does "does not work" mean? Do you get an error (what error?) or do you get some incorrect result (what result?). Also not that you can't test $? twice. The first test would change $?. – Kusalananda Apr 15 '20 at 7:57
  • Sorry, edited original post explaining "does not work". And yes, I know the exit code changes after the first if, I was trying to communicate that both those if's work in terminal. – Morten Apr 15 '20 at 8:02
  • Who's crontab is running the script? – Kusalananda Apr 15 '20 at 8:03
  • root? "sudo crontab -e". – Morten Apr 15 '20 at 8:04
0

I'll answer this myself then - all credits to @steeldriver's comment:
iptables is not in cron's PATH. Changed command to include full path /sbin/iptables.

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.