If there is a file called
new.txt which has permission
-rw-r--r--, but when someone use
chmod 777 new.txt the permissions are changed. Then how to get back the original permissions of new.txt if I do not know the previous permission.
The system won't maintain a history of previous file permissions for you. If you have a backup that includes that file with its original permissions, you might get the original permissions information by listing out the contents of that backup.
Depending of what backup solution you use, you might not even have to restore any actual file: just a directory listing of the contents of a backup with the file permissions included might suffice.
If there is no backup, you must use brainpower to deduce what the permissions should have been. As atype said, the user's
umask setting determines the default permissions for any files or directories the user creates.
For most regular files, the "starting set" of permissions is 666, and then the
umask value is used to mask out some permissions. So if you know that the user's
umask value is 022, then the actual default permissions for the new file would be 666 - 022 = 644, or
Note: the permissions numbers are in octal, and the actual operation uses Boolean operators: 666 AND (NOT 022) = 644.
For directories and executable files, the "starting set" of permissions will be 777 instead of 666. So if the user's
umask is 022, the actual default permissions for a new directory will be 777 - 022 = 755, or
You cannot "get back the original permissions" of a file. What you can do, though, is to set them to whatever the default settings are right now.
touch /tmp/file.$$ # Create a temporary file with "default" perms chmod --ref=/tmp/file.$$ new.txt # "Reset" the file new.txt rm -f /tmp/file.$$ # It's always good to tidy up
The default setting is controlled by the shell's
umask value. On my system, here is the current setting:
This means that write permission (value 02, binary 010) for group and others is to be removed when a file or directory is created.
Also be aware that most editors will not create a file with the executable bit set (binary value 001) even though this should be allowed by the
umask setting. It's up to you as the user to differentiate an ordinary file (without execute permission) and one that is a script (with execute permission):
chmod +x new.txt # Add execute permission