Ubuntu – Set theself as owner of /etc with chown command now getting all kinds of errors

chownownershippermissions

I needed to edit a .config file (which I know for a fact is not creating these problems, just to clear that up) and it wouldn't let me save it, so I took ownership of /etc and all contents with the command chown -hR username /etc and that let me edit the .config file but now whenever I try to install any packages or use any sudo commands, it doesn't work (I've checked for errors in the sudo file in sudoers.d and there was nothing wrong with that).

So how do I return it to the previous owner?

Best Answer

Since some of the files in /etc might not be owned by root, if you want to avoid reinstalling, you can do the following:

  1. Boot into a live system and mount the partition containing the /etc directory. For example, if your / partition is /dev/sda1, you would do this from the live system:

    sudo mount /dev/sda1 /mnt
    
  2. Set the ownership of all files to root:

    sudo chown -R root /mnt/etc
    
  3. At this point all files belong to root. This is probably what you need but some files in /etc/ might have different ownership. If those files are also not owned by root in the live system, you can use them as a reference to change the permissions on the installed system:

    shopt -s globstar
    liveSystem="/etc"
    cd /mnt/etc
    for file in **/*; do 
        [ -e "$liveSystem/$file" ] &&
            echo sudo chown --reference "$liveSystem/$file" "$file"
    done
    

    If you have also changed the permissions, do this instead:

    shopt -s globstar
    liveSystem="/etc"
    cd /mnt/etc
    for file in **/*; do 
        [ -e "$liveSystem/$file" ] &&
            echo sudo chown --reference "$liveSystem/$file" "$file" &&
            echo sudo chmod --reference "$liveSystem/$file" "$file"
    done
    

    That will just print what command would be run. Once you've seen what that does and are satisfied that it is correct, remove the echo to make it actually run the commands.

    Now that will iterate over all files, including those whose ownership is root in both directories, but that doesn't matter. You could write a more sophisticated approach but it's not worth it since this will take seconds.

  4. Reboot your machine: everything should be back to normal.

IMPORTANT: this will not help if you have installed something that isn't on the live system and whose files in /etc don't belong to root. If this is the case, you'll either need to find what you installed and reinstall it or you might need to reinstall the system.