shell Bash if条件以删除特定日期的旧用户

mcdcgff0  于 2022-12-19  发布在  Shell
关注(0)|答案(1)|浏览(83)

我正在写一个bash脚本来获取使用rest api的用户列表,并删除6个月内不活跃的用户。为此,我提取了json数据并获取了名称和日期字段。现在我正尝试写一个if条件来删除6月份以来不活跃的用户。但是条件不起作用。有人能帮忙吗?

userlist="2022-4-30
date= date -d "-6 month" +%Y-%m-%d
if [[ "$userlist" < "$date" ]]
then
  echo "Inactive user. Delete it"
else
  echo "Don't delete"
fi

谢谢大家!

rjzwgtxy

rjzwgtxy1#

您的格式不匹配,并且您正在进行字符串比较。
如果你的格式匹配的话,可能会有用-

$: [[ 2022-4-30 < 2022-06-15 ]] && echo older || echo nope 
nope

$: [[ 2022-04-30 < 2022-06-15 ]] && echo older || echo nope
older

月份没有前导零,并且在任何字符串基本匹配中4都大于0
不过,最好还是换成实际的数学,这太脆弱了。
将格式更改为纪元秒,并使用((...))而不是[[ ... ]]进行测试。

$: cat ckdt
#!/bin/bash
cutoff=$( date -d "-6 month" +%s )               # get base for compares
for m in 7 6 5 4                                 # generate samples to test
do test_date=$( date -d "-$m month" +%Y-%m-%d )  # get an input date
   printf "%s: " "$test_date"                    # show the generated date
   testval=$( date -d "$test_date" +%s )         # convert to epoch seconds
   if ((testval < cutoff))                       # simple math comparison
   then echo "Inactive user. Delete it"
   else echo "Do not delete"
   fi
done

请注意,如果不指定时间,H:M:S默认为00:00:00,并且<不是<=,因此6个月前的采样日期 * 正好 * 是截止时间戳,并且不 * 小于 *,因此它要求删除它。

$: ./ckdt
2022-05-15: Inactive user. Delete it
2022-06-15: Inactive user. Delete it
2022-07-15: Do not delete
2022-08-15: Do not delete

相关问题