SH

Permissions & Ownership

Bash & Linux · 8 entries

Change Permissions (Numeric)

syntax
chmod [options] mode file...
example
chmod 755 deploy.sh
chmod 644 index.html
chmod -R 750 /opt/app/

Note Digits represent owner/group/others. Each is a sum: read=4, write=2, execute=1. So 755 = rwxr-xr-x, 644 = rw-r--r--. Common modes: 755 for scripts/directories, 644 for regular files, 600 for private keys.

Change Permissions (Symbolic)

syntax
chmod [who][+/-/=][permissions] file...
example
chmod u+x build.sh
chmod go-w config.yml
chmod a+r public/favicon.ico

Note who: u=user/owner, g=group, o=others, a=all. Operators: + adds, - removes, = sets exactly. Symbolic mode is safer for targeted changes because you modify only what you specify, unlike numeric which replaces all bits at once.

Change File Owner

syntax
chown [options] user[:group] file...
example
sudo chown www-data:www-data /var/www/html -R
sudo chown deploy app/
sudo chown :staff shared/

Note Requires root/sudo for files you do not own. user:group changes both at once. :group (with colon, no user) changes only the group. -R applies recursively. Be careful with -R on directories containing symlinks; use --no-dereference to avoid following them.

Change Group Ownership

syntax
chgrp [options] group file...
example
sudo chgrp developers /opt/shared-repo -R

Note Equivalent to chown :group. -R applies recursively. You can only change to a group you belong to unless you are root.

Set Default Permission Mask

syntax
umask [mode]
example
umask
umask 027
output
0022

Note umask is subtracted from maximum permissions (777 for dirs, 666 for files). Default umask 022 means new files get 644 and new directories get 755. A umask of 027 gives files 640 and dirs 750, hiding content from 'others'.

Execute as Superuser

syntax
sudo [options] command
example
sudo apt update
sudo -u postgres psql
sudo !!

Note sudo !! reruns the last command with sudo (great when you forget to prefix it). -u runs as a specific user. Sudo access is configured in /etc/sudoers (edit only with visudo, never directly). Your password is cached for a short time after the first entry.

Switch User

syntax
su [options] [user]
example
su - deploy
su -c 'systemctl restart nginx' root

Note su - (with the dash) starts a login shell and loads the target user's environment. Without the dash, you inherit the current environment. -c runs a single command as that user and returns.

Special Bits: Sticky, SUID & SGID

syntax
chmod [1|2|4]nnn file
chmod +t directory
chmod g+s directory
example
chmod 1777 /tmp
chmod 2775 /opt/team-share/
chmod u+s /usr/bin/passwd

Note Sticky bit (1 or +t): only the file owner can delete their files in a shared directory (used on /tmp). SGID (2 or g+s) on a directory: new files inherit the directory's group. SUID (4 or u+s) on an executable: it runs as the file owner, not the caller. SUID/SGID are security-sensitive; audit carefully.