Undoing a chown -R is tricky because Linux does not keep a history or "undo log" of ownership changes. Once the command finishes, the system doesn't remember who the previous owners were.
To "undo" the changes, you have to manually set the ownership back to what it was. Based on our current lab step, here is how you can handle it:
1. The Manual Reversal (For this Lab)
In the previous step, we changed everything in new-dir to root. To "undo" this and give ownership back to the labex user, run:
sudo chown -R labex:labex new-dir
2. If you don't know the previous owner
If you accidentally changed ownership and aren't sure who the owner was, you can try these approaches:
- Check similar files: Look at other files in the same parent directory using
ls -l. Usually, files in a project folder belong to the same user. - The
--referenceflag: If you have another file or directory that still has the "correct" ownership, you can use it as a template:
This tells Linux: "Make everything insudo chown -R --reference=/home/labex/project/some_other_file new-dirnew-dirhave the same owner/group assome_other_file."
3. The "Nuclear" Option (For System Files)
If you accidentally ran chown -R on a system directory (like /etc or /usr) and broke the OS:
- There is no easy "undo" command.
- System administrators usually have to restore from a backup.
- In some Linux distributions (like Fedora/CentOS), you can use package managers (like
rpm) to reset permissions/ownership to the defaults defined in the packages, but this is an advanced recovery step.
Labby's Tip: Before running a recursive command on a folder with many different owners, you can "back up" the current permissions to a file using a tool called getfacl:
getfacl -R folder_name > permissions_backup.txt
If you mess up, you can restore them with:
setfacl --restore=permissions_backup.txt
(Note: You might need to install acl to use these commands, but it's a great habit for real-world servers!)