Linux: Number of days before password expires

While creating a script to send an email alert when a linux accounts password is about to expire, we needed to determine the number of days remaining before expiry. A quick search of Google surprisingly returned only methods that access /etc/shadow, which is not possible for standard users. However, we did manage to come up with a solution.

The following can be used to echo the number of days remaining to stdout:

EXPIRE_DATE=$(chage -l $USER | awk -F ':' '/^Password expires/ { print $NF }')
[[ $(echo $EXPIRES | grep -c 'never') -gt 0 ]] && echo "never" ||  echo "( $(date -d "$EXPIRE_DATE" "+%s") - $(date +%s) ) / 86400" | bc

It's worth mentioning the "-d" option of the date command that allows a human readable date to be passed in - which is automatically parsed without needing to specify a format specification.

Very useful!