我正在做一個腳本來評估用戶的最后一次連接,為此,我得到了最后一次連接的時間,我提取了用戶 最后一次連接的日期,我現在需要做的是看看是否例如,日期大于或小于“2022-05-20”,但我的問題是,我不知道如何在 bash 中比較兩個日期。
這是我的代碼;
while [ $i -le $size_students ]
do
# Get the user's login
login=$(sed -n "${i}p" xxxx.txt)
# Get the user's data
user_data=$(curl -X GET -H "Authorization: Bearer ${bearer_token}" "https://xxxxxxxxx/${login}/locations_stats" --globoff)
# Get the user's last location
last_lotaction=$(echo $user_data | jq -r '.' | cut -d "\"" -f 2 | grep -Eo '[0-9]{4}-[0-9]{2}-[0-9]{2}' | head -n 1)
# if last_location is null or less than 2022-05-01, the user is not connected
echo `$login: $last_location`
輸出是:
EnzoZidane: 2022-03-17
uj5u.com熱心網友回復:
使用您的日期格式,簡單的字串比較應該會產生所需的結果:
#!/bin/bash
[[ 2022-05-20 > 2022-05-19 ]] && echo yes
[[ 2022-05-20 < 2022-05-19 ]] || echo no
uj5u.com熱心網友回復:
如果您可以保證所有月份和日期都在適用的情況下使用前導零進行格式化,并且順序是年-月-日,那么您可能只使用字串比較:
if [[ "2022-05-31" < "2022-06-01" ]]
then
echo true
fi
uj5u.com熱心網友回復:
將所有日期轉換為epoch第一個,然后您可以比較兩個整數:
if [[ $(date --date="$last_location" %s) < $(date --date="2022-05-20" %s) ]]; then
echo "before"
else
echo "after"
fi
紀元時間始終是整數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/487309.html
上一篇:使用sed進行欄位排序
