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
- printing iptables in terminal both seconds before and after a scheduled run
- 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
$?
twice. The first test would change$?
. – Kusalananda Apr 15 '20 at 07:57iptables
is not in cron'sPATH
(so that you're testing the exit status of a failediptables
command, rather than the exit status ofgrep
)? Try adding the full path ex./sbin/iptables
– steeldriver Apr 15 '20 at 11:19echo $var
instead ofecho "$var"
resulted in a mucked up mixture of the actual iptable and folder names/paths from ~ ... – Morten Apr 15 '20 at 12:07sudo
in the script itself. – Chris Davies Apr 16 '20 at 12:20