Linux file permissions and ownership
Read and set rwx permissions with numbers or letters, change owners with chown, and avoid the chmod 777 habit.
Permission questions appear in almost every Linux screening because support staff meet them daily: a script that will not run, a web server that cannot read a file, a log a user cannot open. Once you can read the permission string, most of these problems become quick to diagnose.
Reading the permission string
Run ls -l and you will see something like this:
-rwxr-x--- 1 alice dev 2048 Mar 3 10:15 deploy.sh
The first character is the type: - for a file, d for a directory. The next nine characters are three groups of three: owner, group and others. Here alice can read, write and execute, members of dev can read and execute, and everyone else has no access.
On a directory, the letters mean slightly different things. Read lets you list the names inside, write lets you create and delete files inside, and execute lets you enter the directory with cd. A directory without execute permission cannot be used even if read is set.
Numeric mode
Each permission has a value: read is 4, write is 2 and execute is 1. Add them for each class.
chmod 755 script.shgives rwxr-xr-x, a common setting for programs.chmod 644 notes.txtgives rw-r--r--, a common setting for normal files.chmod 600 id_rsagives rw-------, which private keys need.
Symbolic mode and ownership
Symbolic mode changes one thing without touching the rest. Use u, g, o or a, then +, - or =, then the letters. For example, chmod u+x deploy.sh adds execute for the owner and chmod o-r report.txt removes read for others.
Ownership is changed with chown, which usually needs sudo. chown alice:dev report.txt sets both owner and group, and chown -R www-data:www-data /var/www/site applies the change to a whole folder.
Common mistakes
- Using
chmod 777to make an error go away. It lets every user change the file and hides the real cause. - Forgetting that a script also needs execute permission, not only read.
- Fixing permissions on a file when the problem is a parent directory without execute permission.
Habit: before changing anything, run ls -l on the file and ls -ld on its parent directory, note who the process runs as, and then give the smallest permission that solves the problem.
More in Cloud and DevOps