Fix files with ????????? permissions

chmodchownpermissions

I wrote a script to change permissions on all files in a directory:

#!/bin/bash

files=`find "$1"`

for f in $files; do
    chown "$2" "$f"
    chmod 600 "$2"
done

Obviously, the second argument to chmod should be "$f" instead of "$2". However, when I ran the script (on a small directory) I also forgot to include the second argument, which should have been "dave:dave". Now, all the files in the directory are completely messed up:

~ $ ll Documents/                                                                                                      
ls: cannot access Documents/wiki.txt: Permission denied
ls: cannot access Documents/todo.txt: Permission denied
ls: cannot access Documents/modules.txt: Permission denied
ls: cannot access Documents/packages.txt: Permission denied
total 0
-????????? ? ? ? ?            ? modules.txt
-????????? ? ? ? ?            ? packages.txt
-????????? ? ? ? ?            ? todo.txt
-????????? ? ? ? ?            ? wiki.txt

Running sudo chown dave:dave Documents/* and sudo chmod 600 Documents/* throws no errors, but the files remain unchanged. I know I can sudo cat each file into a new file, but I'm curious how to fix the permissions on the original files.

Best Answer

In addition to the answers given in the comments, you should also note that your script will break on any filenames with spaces in them.

You can do all of this in a single command using find, rather than trying to parse a list of filenames output from find. Much more robust; handles filenames regardless of special characters or whitespace.

find "$1" -type f -exec chown "$2" {} \; -exec chmod 600 {} \;

Note that if the chown fails on a given file, the chmod will not be run on that file. That's probably the behavior you want anyway.


Since you already ran an erroneous command that removed execute permissions from your "Documents" directory, you need to add back execute permissions:

chmod u+x Documents

If there are more directories that erroneously had execute permissions removed, you should be able to fix them with:

find Documents -type d -exec chmod u+x {} \;

I don't think you'll need this, though, as once execute permissions were removed from "Documents" then none of its subdirectories would be accessible, so execute permissions wouldn't have been removed from them.

Related Question