I have a script that programmatically creates users, but we'd like to delete the users after 48 hours, as well as any files they own.

I know you can set an expiration with the useradd command, but I don't know how to take the next step of deleting the user and its associated files on expiration.

Is there an easy way to do this?

Thank you!


Assuming you have a user creation script that sets $username, add this:

cat <<EOF | at now + 2 days
userdel -f -r $username

It also pays to set an expiration on the account when it is added, as extra insurance.


If you are setting up accounts to expire 2 days after you set them up then the script below should help.

nowsecs=$( date +%s )

while read account
    username=$( echo $account | cut -d: -f1  )
    expiredays=$( echo $account | cut -d: -f2 )
    expiresecs=$(( $expiredays * 86400 ))
    if [ $expiresecs -le $nowsecs ]
        echo "$username has expired deleting"
        userdel -r "$username"
done < <( cut -d: -f1,8 /etc/shadow | sed /:$/d )

When it's run it reads the shadow file and selects accounts with expiry dates set. For each selected account it works out if now is later than the expiry time. If it is it deletes the account.

Making sure you have backups before testing this.


Probably a good idea would be to use a mixture of crontab + file containing usernames to delete? Delimit that file with necessary dates maybe, or run a cron job that looks for expired users and deletes them. A simple shell script can do this.


If you are already marking them as "expired" you could try a cron task to schedule daily, hourly or weekly account cleanups. You just create a script just like the one you wrote to create the user, but to detect expiration and delete whatever you need to. Make sure it runs as root.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.