How can I automate clearing and resetting a Linux user's home directory to a default?

There are many ways that would help:

  • remove the complete home directory and copy all files from /etc/skel back to the homedir. Change permissions afterwards.
  • put the system in a virtual machine, make a snapshot and revert to the snapshot after lesson 1
  • find something like a kiosk mode in RHEL. Ubuntu has something like that, which automatically restores the home during logoff
  • put the home on a btrfs filesystem, make a snapshot and revert after lesson 1
  • tar the home dir before lesson, delete home afterwards, restore from tar
  • ...

And learning other tools like Puppet/Chef is a little bit too much if you want results next week.


Lets say all your students had a UID between 1000 and 65000

A quick one-liner like this would work. Awk will print out an rsync command and chown command for every user in the range. Sending the output of the awk into bash will run the all the commands to reset directories and permissions.

# see what will happen.
awk 'BEGIN{FS=":"} $3 >= 1000 && $3 <=65000 { print "rsync --delete -v -r /etc/skel/ " $6 "/ ; chown -R " $1 ":" $1 " " $6;}' /etc/passwd

# actually run the commands to reset all users matched by awk.
bash <( awk 'BEGIN{FS=":"} $3 >= 1000 && $3 <=65000 { print "rsync --delete -v -r /etc/skel/ " $6 "/ ; chown -R " $1 ":" $1 " " $6;}' /etc/passwd )

If you're using gdm for your login manager you can add something like this file: /etc/gdm/PostSession/Default

#!/bin/sh

if [[ "$USER" != "" ]]; then
   rm -rf /home/$USER
   cp -r /etc/skel /home/$USER
   chown -R $USER:$USER /home/$USER
fi