Command linemediumBash

File Permission Management

Common commands for managing file permissions and ownership in Unix systems.

01

The problem

You need to set proper file permissions for scripts, web files, or executables.

02

The solution

Bash
# Change permissions using symbolic mode
chmod u+x file.sh      # Add execute for user
chmod go-w file.txt    # Remove write for group and others
chmod a+r file.txt     # Add read for all (user, group, others)

# Change permissions using numeric mode
chmod 755 script.sh    # rwxr-xr-x (user: rwx, group: r-x, others: r-x)
chmod 644 config.txt   # rw-r--r-- (user: rw-, group: r--, others: r--)
chmod 600 private.key  # rw------- (user only)
chmod 777 dangerous.sh # rwxrwxrwx (NOT recommended)

# Change ownership
sudo chown user:group file.txt
sudo chown -R www-data:www-data /var/www  # Recursive

# Change group only
sudo chgrp developers project/

# Set sticky bit (directory)
chmod +t /shared/directory

# Set SUID/GUID
chmod u+s /usr/bin/program  # SUID
chmod g+s /shared/dir       # GUID

# View permissions in detail
ls -la
stat file.txt

03

Put it to work

Example
# Make script executable
chmod +x deploy.sh

# Secure SSH keys
chmod 600 ~/.ssh/id_rsa
chmod 644 ~/.ssh/id_rsa.pub
chmod 700 ~/.ssh

# Web directory permissions (common)
sudo chown -R www-data:www-data /var/www/html
find /var/www/html -type d -exec chmod 755 {} \;
find /var/www/html -type f -exec chmod 644 {} \;

Worth knowing

Numeric mode: 4=read, 2=write, 1=execute. First digit: SUID/GUID/sticky, second: user, third: group, fourth: others.