格式化 chage 命令日期输出

Rom*_*dgz 3 command-line bash scripts password

我想要一个脚本来直观地警告我系统上的用户他们的密码即将过期。我在这里找到了这个。

问题是,该脚本的作者通过将日期转换为秒、减去秒并将其传递为天来获取密码过期的天数。

问题是我的系统将这些日期输出为“2018 年 8 月前”(今天)。如果我像作者一样坚持使用 date 命令将日期转换为秒,则会收到错误:无效日期“2018 年 8 月 8 日之前”。

有什么帮助吗?

这是完整的脚本:

#! /bin/bash
# Issue a desktop notification if the user password is about to expire
# Uses the "chage" command frome the "passwd" package (likely installed)
# Best added to the session startup scripts

# get password data in array
saveIFS=$IFS
IFS=$'\n'
chagedata=( $(chage -l $USER | cut -d ':' -f 2 | cut -d " " -f 2-) )    
IFS=$saveIFS

# obtain times in seconds
now=$(date +%s)
expires=$(date +%s -d "${chagedata[1]}")

# compute days left (roughly...)
daysleft=$(( ($expires-$now)/(3600*24) ))
echo "Days left: $daysleft" 
# leave some evidence that the script really ran at startup
echo "Days left: $daysleft" > /var/tmp/$(basename $0).out

# determine and send the notification (stays mute if outside the warning period) 
if [[ $daysleft -le 0 ]]
then
    notify-send -i face-worried.png -t 0 "Password expiration" "Your password expires within a day"'!' 
elif [[ $daysleft -le ${chagedata[6]} ]]
then
    notify-send -i face-smirk.png -t 0 "Password expiration" "Your password expires in $daysleft days."
fi
Run Code Online (Sandbox Code Playgroud)

dan*_*zel 5

根据date文档,当前输入必须采用与语言环境无关的格式。他们建议使用来生成独立于区域设置的日期输出。在您的情况下,您必须在命令前面添加命令以使其输出能够解析的日期字符串:LC_TIME=Cchagedate

chagedata=( $(LC_TIME=C chage -l $USER | cut -d ':' -f 2 | cut -d " " -f 2-) )
Run Code Online (Sandbox Code Playgroud)