Unix

sh 腳本如何確定它是作為 cron 作業而不是互動式或後台作業啟動的?

  • August 21, 2013

我想對 cron 和互動式使用相同的腳本,只是想知道是否有一種通用的方法可以在 UNIX/Linux 系統上輕鬆做出這個決定。

您可以嘗試使用以下內容返回父程序的名稱:-

ps -ocommand= -p $PPID | awk -F/ '{print $NF}' | awk '{print $1}'

對我來說,當我以互動方式執行它時,它返回了konsole 。

或者您可以編寫一些邏輯腳本來處理情況。

while getopts cm opt
do
case $opt in
       c)
               ##  Do crontask 
       ;;
       m)
               ##  Do manual
       ;;
       esac
done

現在,在執行腳本時,您可以將選項作為屬性傳遞,如下所示:-

/use/local/bin/example.sh -m
/use/local/bin/example.sh -c

根本沒有通用的方法。使用互動式/非互動式 shell 檢測或 tty 檢測也不可靠,因為 cron 以外的其他情況可能具有這些特徵。只需在您的 cron 條目中添加一個變數。說你需要執行 test.sh,然後改用它。

$ RUNENV=cron ./test.sh
cron
cat ./test.sh 
#!/bin/sh
echo $RUNENV

如果您控制 cron 設置,這是相當簡單和可靠的。

引用自:https://serverfault.com/questions/532453