簡體   English   中英

如何在bash腳本中的IF函數中獲取特定的日期和時間

[英]How to get specific dates and times within an IF function in bash script

我正在嘗試獲取具體日期和時間,以便從下面的代碼中獲得三種不同的結果。 有時不能正常工作,所以可能做錯了。

#!/bin/bash
currentdate=6
currenttime=17
if [[ ${currentdate#0} -ge  5 ]] && [[ ${currenttime#0} -ge 18 ]] && [[ ${currentdate#0} -le 7 ]] && [[ ${currenttime#0} -le 22 ]]
then
echo "command for Friday after 18pm until Sunday 22pm"
elif [[ ${currentdate#0} -eq 3 ]] && [[ ${currenttime#0} -ge 18 ]] && [[ ${currenttime#0} -le 20 ]]
then
echo "command for Wednesday after 18pm until 20pm"
else
echo "command for all other dates and times"
fi

我的功能出現了邏輯錯誤。 通過將其更改為:

if [[ ${currentdate#0} -ge  5 ]] && [[ ${currenttime#0} -ge 18 ]] || [[ ${currentdate#0} -eq  6 ]] || [[ ${currentdate#0} -le 7 ]] && [[ ${currenttime#0} -le 22 ]]

您可以將日期編號和小時合並為一個數字,並將其作為一個整體進行比較。 使用此方法,您可以根據需要定義任何時間范圍。

僅使用一個日期命令而不是兩個具有避免可能的錯誤結果的優點,當第一個在23:59被調用而第二個在第二天的0:00被調用時。

使用格式%H打印的小時有兩位數字(00..23),因此您將始終獲得3位數字。 小時數最多只計算到23小時並不重要。小時23的當前日期將小於第二天小時00.星期幾格式%u打印范圍內的數字(1..7 ),因此得到的數字不會有前導0。

daytime=$(date +%u%H)

if [ "${daytime}" -ge  518 ] && [ "${daytime}" -le 722 ]
then
    echo "command for Friday after 18pm until Sunday 22pm"
elif [ "${daytime}" -ge 318 ] && [ "${daytime}" -le 320 ]
then
    echo "command for Wednesday after 18pm until 20pm"
else
    echo "command for all other dates and times"
fi

注意:該腳本基於問題的原始腳本。 我沒有改變可以改進的一切。
除了"${daytime}"您還可以在此特定情況下使用"$daytime"$daytime${daytime} 該報價將有助於獲得的情況下,有一個與的分配錯誤更好的錯誤消息, date結果daytime導致錯誤或空值daytime在此腳本date命令將始終打印不帶空格的3位數字,所以腳本沒有引號。
有些人喜歡使用帶有所有可變擴展的大括號,有些則不喜歡,所以這里的味道很重要。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM