【问题标题】:Compare a date in a bash script比较 bash 脚本中的日期
【发布时间】:2022-10-23 02:23:20
【问题描述】:

我正在编写一个脚本来评估用户的最后一次连接,为此,我得到了最后一次连接的时间,我提取了用户+最后一次连接的日期,我现在需要做的是看看是否例如,日期大于或小于“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

【问题讨论】:

  • “我提取用户+上次连接的日期”好的,但是那个日期的格式是什么?
  • 请将脚本和问题减少到显示您的问题所需的最低限度。有很多额外的代码对于问题来说是不必要的。
  • 如果您可以保证您所有的月份和日期都在适用的情况下使用前导零进行格式化,顺序是年月日,那么您可能只需要进行字符串比较:"2022-05-31" < "2022-06-01" 评估为真,我想。
  • 脚本已更新,我减少代码,感谢帮助
  • 我只想知道 $last_location 是主要还是小于 X 日期

标签: bash shell date


【解决方案1】:

使用您的日期格式,简单的字符串比较应该会产生所需的结果:

#!/bin/bash
[[ 2022-05-20 > 2022-05-19 ]] && echo yes
[[ 2022-05-20 < 2022-05-19 ]] || echo no

【讨论】:

  • 不起作用,如果 [[$last_location < "2022-05-01"]]
  • never_connected_students.sh:第 55 行:2022-05-01]]:没有这样的文件或目录
  • 不要去掉[[]] 周围的空格。 [[$last_location &lt; "2022-05-01"]][[ $last_location &lt; "2022-05-01" ]] 的含义不同
  • if [ "$last_location" < "2022-05-01" ] and never_connected_students.sh: line 55: 2022-05-01: No such file or directory
  • @Bart 使用双 [[]]
【解决方案2】:

如果您可以保证您所有的月份和日期都在适用的情况下使用前导零进行格式化,顺序是年月日,那么您可能只使用字符串比较:

if [[ "2022-05-31" < "2022-06-01" ]] 
then 
    echo true
fi

【讨论】:

  • 不工作:(
  • @Bart 如何“不起作用”?以上产生“真”作为输出,如果我将&lt; 更改为&gt;,它不会,所以它似乎工作。
【解决方案3】:

首先将所有日期转换为epoch,然后您可以比较两个整数:

if [[ $(date --date="$last_location" +%s) < $(date --date="2022-05-20" +%s) ]]; then
    echo "before"
else
    echo "after"
fi

纪元时间始终是整数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-29
    • 1970-01-01
    • 1970-01-01
    • 2013-01-26
    • 1970-01-01
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多