scheduled-tasksat-jobcommand-substitution

This statement runs interactively but not from 'at' scheduled


if [ $(/sbin/iptables -w -L INPUT -n|grep --line-buffered -m 1 -c -w 66.128.56.213) == "0" ]; then /sbin/iptables -w -I INPUT "$(/sbin/iptables -w -L INPUT -n --line-numbers|stdbuf -o0 grep -m 1 -w DROP|stdbuf -o0 awk  '{print $1}')" -i eth0 -s 66.128.56.213 -m comment --comment 'kern.log Oct 27 23:14:10 PROTO=UDP SPT=5118 DPT=5060' -j DROP;fi

Ubuntu headless 15.10: The above statement was scheduled in 'at' by my script I am developing. It did not do the expected iptables insert task when it ran because the comparison within the brackets is false (I used an else, not shown, to learn that). I have tried changing the quoting of the zero...no quotes, single quotes and double quotes. I know the value prior to the '==' is 0 because I inserted this in the constructed, scheduled command prior to what is shown above: echo $(/sbin/iptables -w -L INPUT -n|grep --line-buffered -m 1 -c -w 66.128.56.213) >> /home/mydir/testfile.txt

and it echo'd a simple 0 into the file. And if I just try 0 == 0 in the brackets, it computes as false also. Can anyone see why I can't compare two zeros to be the same as each other? And how can I make my desired statement branch the way I want it to: when the substituted command equates to zero? It acts differently, and correctly as expected, from the command line. My guess is a shell difference. I tried using double brackets. No luck. ([]) doesn't work, either. Neither does using eq in place of ==.


Solution

  • @abligh, Thank you for trying. The answer is found in the warning that you'll only see when loading 'at' commands interactively:

    `warning: commands will be executed using /bin/sh'
    

    Correct syntax for this in /bin/sh is:

    if [ $(/sbin/iptables -w -L INPUT -n|grep --line-buffered -m 1 -c -w 66.128.56.213) -eq 0 ]; then...

    The grep output is numeric, not text, so quotes are removed, and the '==' is replaced by '-eq', and the 'if' is optional.