linux - 如何修复密码过期脚本中的无效日期错误

标签 linux bash shell

我试图编写一个 bash 脚本来通知即将过期的用户密码。我在与“从不”进行字符串比较时遇到问题。我该如何避免这种情况?

我提到了 Shell script to send email before password expires并稍微调整了一下。但是我在字符串比较时遇到了问题。如果 $userexp 等于 never,我打算跳过代码执行。但是它没有发生并继续执行下一部分代码并且我收到以下错误 日期:无效日期“从不”

#!/bin/bash
#

user=user
HOST=`uname -n`
  # convert current date to seconds
  currentdate=$(date +%s)

  # find expiration date of user
  userexp=$(chage -l $user | grep 'Password expires' | cut -d: -f2)

  if [[ ! -z $userexp ]]
  then
    # convert expiration date to seconds
    #passexp=$(date -d "$userexp" "+%s")

    if [ "$userexp" = "never" ]
    then
       echo "Password for $user in $HOST is set to never expire"
   else
    # convert expiration date to seconds
    passexp=$(date -d "$userexp" "+%s")

      # find the remaining days for expiry
      (( exp = $passexp - $currentdate ))

      # convert remaining days from sec to days
      (( expday =  $exp / 86400 ))

      if (($expday < 10 ))
      then
        echo "Password  for $user in $HOST will expire in $expday day/s"
          else
          echo "Password for $user in $HOST still have much time to expire"
          fi
     fi
   fi

为什么我的字符串比较没有按预期工作,我该如何解决。

最佳答案

如果 $userexp 等于“从不”你的代码,即使不是你能做出的最好的代码(无意冒犯 :)),应该可以工作。它认为您的案例中可能有一个前导空格,即 _never 其中 _ 是空格。检查一下,如果是这种情况,请将 if 条件中的 "never" 更改为 "never"

关于linux - 如何修复密码过期脚本中的无效日期错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57558752/

相关文章:

linux - Ubuntu 18.04 Bionic Beaver(开发分支)现在稳定了吗?

regex - 将终端命令分配给 bash 变量时出错

bash - 找不到命令时的安全 shell 重定向

bash - Perl Regex Query - 过滤文件中超过 18 个月的内容

arrays - Bash、数组和空格的奇怪行为

linux - ubuntu启动黑屏

linux - shell命令的含义和htaccess文件?

javascript - NPM rimraf - 文件夹丢失时继续执行(停止退出代码 1)

c# - 我们应该在哪里寻找 C++ 常量? (出现在 MSDN 文档中)

c - fatal error : sys/socket. h:32 位上没有这样的文件或目录