After this lesson, you will be able to: Read and modify Linux file permissions: rwx, the octal model, ownership with chown, and when to use sudo.
File permissions are the most-misunderstood part of Linux. Master them and most 'permission denied' headaches vanish.
Every file has nine permission bits, three groups of three: Owner (the user who owns it) read/write/execute. Group (the group that owns it) read/write/execute. Other (everyone else) read/write/execute. `ls -l` shows them as `-rwxr-xr--`. The first char is file type (`-` regular, `d` directory, `l` symlink).
Read this line by line until the format clicks.
$ ls -l deploy.sh-rwxr-xr-- 1 alex devs 4096 Mar 12 14:33 deploy.sh# Breakdown:# - regular file (d = dir, l = symlink)# rwx owner can read, write, execute# r-x group can read, execute (not write)# r-- other can read only# 1 number of hard links# alex owner user# devs owner group# 4096 size in bytes# Mar 12 14:33 last modified time# deploy.sh filename
Each permission position is a bit: r=4, w=2, x=1. Add them per role. `chmod 755` = owner: 7 (4+2+1=rwx), group: 5 (4+1=r-x), other: 5 (r-x). The default for executables. `chmod 644` = owner: 6 (rw-), group: 4 (r--), other: 4 (r--). The default for non-executable files. `chmod 600` = owner: rw-, group: ---, other: ---. The default for secrets (SSH keys, env files). Memorise 755, 644, 600. You'll use them daily.
The three commands you'll use to fix 99% of permission problems.
chmod 755 script.sh # set permissions (octal)chmod +x script.sh # add execute for everyonechmod u+x script.sh # add execute for owner onlychmod o-r secrets.txt # remove read for 'other'chmod -R 644 dir/ # recursivechown alex file.txt # change ownerchown alex:devs file.txt # change owner AND groupchown -R www-data:www-data /var/wwwsudo command # run command as root (admin)sudo -i # become root shell (use sparingly)sudo -u alice command # run as different user
`chmod 777 file.txt` to 'fix' a permission issue. Never the answer in production. SSH key with 644 permissions. OpenSSH refuses to use it (must be 600). Editing files in `/etc` as a normal user, then `sudo cp` over (loses ownership). Edit with `sudo nano /etc/...` directly. Forgetting that directory `x` permission controls 'can enter the directory', NOT 'execute as a program'. Granting full sudo to deploy users (instead of specific commands in /etc/sudoers.d/).
Pick the correct command.
Sign in and purchase access to unlock this lesson.