BudiBadu Logo
Samplebadu

Bash by Example: Change Permissions

Bash 5.0+

Modifying file access permissions using chmod command with both symbolic notation for human-readable changes and octal numeric notation for precise control, including common permission patterns for scripts, configuration files, and security-sensitive data.

Code

#!/bin/bash

touch script.sh

echo "1. Symbolic Mode"
# Add execute permission for Owner
chmod u+x script.sh
ls -l script.sh

# Remove write permission for Group and Others
chmod go-w script.sh

# Add read/write for Everyone
chmod a+rw script.sh

echo "2. Octal Mode"
# 755: rwx (7) for owner, rx (5) for group/others
chmod 755 script.sh
ls -l script.sh

# 644: rw- (6) for owner, r-- (4) for group/others
# Standard for regular files
chmod 644 script.sh

# 600: rw- (6) for owner, --- (0) for others
# Private file (SSH keys, secrets)
chmod 600 script.sh

rm script.sh

Explanation

The chmod (change mode) command is the primary tool for modifying file and directory permissions in Unix-like systems. It offers two distinct syntaxes for specifying permissions: symbolic notation and octal (numeric) notation. Symbolic mode is more intuitive for making incremental changes, while octal mode provides a concise way to set all permissions at once.

Symbolic Mode uses letters to represent who is affected and what changes to make:

  • u (user/owner), g (group), o (others), a (all three categories)
  • Operators: + adds permissions, - removes them, = sets exactly
  • Permissions: r (read), w (write), x (execute)
  • Example: chmod u+x,go-w file adds execute for owner and removes write for group and others

Octal Mode uses three-digit numbers where each digit is the sum of permission values. Each digit represents one category (owner, group, others), and each permission type has a numeric value: Read=4, Write=2, Execute=1. For example, chmod 755 file means owner gets 7 (4+2+1=rwx), while group and others get 5 (4+1=r-x). Common patterns include 644 for regular files (owner can read/write, others can only read), 755 for executable files and directories, and 600 for private files like SSH keys.

Code Breakdown

7-8
chmod u+x adds execute permission only for the owner. This is safer than chmod +x (or a+x) which would grant execute to everyone.
11
chmod go-w removes write permission from group and others, a common security hardening step.
18-19
chmod 755 is the standard permission pattern for executable scripts and directories. Owner has full control (rwx), while group and others can read and execute (r-x).
22-27
Common permission values: 644 for regular files, 600 for private files (SSH keys, credentials). The more restrictive, the more secure.