[英]How to run a task at startup between certain times of day in a bash script
我的目標是在一天中的兩個特定時間之間啟動時啟動一個任務(具體來說,一個 package 在 Linux Mint 21 中運行),或者如果計算機已經在運行,則在啟動時間啟動,在結束時間停止。 我知道如何完成這三個任務中的兩個,在啟動時運行並在 cron 腳本中的某個 tod 運行,但我不知道如何將所有三個語句組合在 bash 腳本中以在 cron 作業中引用。
謝謝
我在 inte.net 上查找了各種解決方案,包括詳細介紹 bash 腳本中的 if 和 while 語句的頁面,以及 cron 中的各種選項。 沒有一個足夠具體。
我希望我的 bash 腳本滿足上述條件並插入到 cron 文件中。
“在啟動時”和“在 cron 作業中”不太適合結合使用。
在您的“啟動時”腳本中,只需檢查時間。 假設你的意思是“如果當前時間是早上 8 點到下午 5 點”,那么我會做這樣的事情 -
在上午 11 點運行這些。
早上 8 點到 10 點,
$: declare -A span=();
$: for hr in {08..10}; do span[$hr]=1; done
$: ((${span[$(date +%H)]})) && echo do the thing || echo not doing the thing now
not doing the thing now
早上 8 點到下午 5 點,
$: declare -A span=(); # make a lookup tab;le
$: for hr in {08..16}; do span[$hr]=1; done # populate it
$: ((${span[$(date +%H)]})) && echo do the thing || echo not doing the thing now
do the thing
你也可以這樣做
$: now=$(date +%H); (( now >= 10#08 && now <= 10 )) && echo doing || echo not doing
not doing
$: now=$(date +%H); (( now >= 10#08 && now <= 16 )) && echo doing || echo not doing
doing
(其中的10#08
是為了確保帶前導零的兩位數字仍被解析為基數 10 而不是八進制。)
或者您可以使用case
陳述。
$: case $(date +%H) in 08|09|10 ) echo doing;; *) echo not doing;; esac
甚至(如果你的版本足夠)
$: case $(date +%H) in
08) ;&
09) ;&
10) ;&
11) ;&
12) ;&
13) ;&
14) ;&
15) ;&
16) echo doing ;; # fall through with ;& lines in a case statement
*) echo NOT doing ;; esac
doing
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.