cron - bash 腳本,帶有有關退出程式碼和 grep 的 if 語句

cron - bash 腳本,帶有有關退出程式碼和 grep 的 if 語句

我在 Linux 和 bash 領域相對“初學者”,我無法弄清楚這一點。

除此之外,如果“字串”不存在,我想修改 iptables,但它似乎不起作用。不確定這是否是因為 if 語句、退出程式碼、語法或 sudo 權限或其他原因。

當腳本透過 cron 自動運行時,if即使iptables包含我正在尋找的字串,它也會執行該子句。這是透過驗證

  1. 在計劃運行之前和之後幾秒在終端中列印 iptables
  2. echo "this" >>/log/file.log透過在 if 子句中新增一個。

取1:

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

取2:

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

我已經嘗試過這兩種方法,由 (sudo) crontab 使用以下行觸發:

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

讓我感到困惑的是,當直接輸入終端時,上面的兩個選項似乎都有效,如下所示:

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

是什麼賦予了?

如果相關的話,我的系統是新的 Linux Mint 19.3 Tricia

答案1

那麼我自己來回答這個問題 - 所有學分@steeldriver評論:
iptables不在 cron 中PATH。更改命令以包含完整路徑/sbin/iptables

相關內容