Website Vidya
SecurityStep-by-Step Guide

chmod Command in Linux: Syntax, Flags & Practical Guide

Learn chmod command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

RR
Rajesh RayLead Systems Educator
Published:
10 min read
PDF Cheat Sheet
chmod Command in Linux: Syntax, Flags & Practical Guide
AI Executive SummaryWebsiteVidya AI

10 min read

Learn chmod command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What chmod Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

Operating systems built on the Unix architecture enforce access boundaries through discretionary access control (DAC), and the chmod command in linux serves as the primary utility for modifying these discretionary permission bits. Short for 'change mode', chmod alters the 12 permission mode bits stored within a filesystem inode.

Every file and directory in Linux has distinct permissions assigned to three authorization scopes: the user who owns the file (u), the group associated with the file (g), and all other users on the system (o). By adjusting Read (r), Write (w), and Execute (x) bits—as well as special flags including SUID, SGID, and the sticky bit—administrators control who can inspect data, modify state, or run binaries.

Whether configuring an unprivileged daemon service, making automation scripts executable, securing SSH private keys, or auditing file access across multi-user servers, mastering both numeric octal and symbolic chmod syntax is an indispensable skill.

Advertisement
chmod Command in Linux: Syntax, Flags & Practical Guide — syntax, flags, and practical terminal workflow diagram
chmod Command in Linux: Syntax, Flags & Practical Guide — command syntax, key options, and production workflow reference.

What chmod Does and When to Use It

Under the hood, executing chmod triggers the fchmodat(2) system call in the Linux kernel (or chmod(2) on older architectures). The kernel verifies that the caller's effective UID (EUID) matches the file owner (i_uid) or that the calling process possesses the CAP_FOWNER Linux capability (typically granted to root). If this verification passes, the kernel writes the new 12-bit mode value into the inode's i_mode structure and marks the inode dirty for filesystem journaling.

The lower 9 bits correspond to user, group, and other permissions, while the upper 3 bits represent special modes: Set User ID (SUID, 04000), Set Group ID (SGID, 02000), and the Sticky Bit (01000). When SUID is set on an executable binary, the kernel executes the process with the privileges of the file owner rather than the calling user (as with /usr/bin/passwd). When SGID is set on a directory, newly created files automatically inherit the parent directory's group ID rather than the creator's primary group.

Linux enforces discretionary access control (DAC) by evaluating the effective User ID (EUID), effective Group ID (EGID), and supplementary groups against inode permission bits. When chmod executes, the Virtual File System (VFS) and active Linux Security Modules (SELinux or AppArmor) validate the caller's privileges before committing changes to disk or account databases.

Availability and Installation Across Linux Distributions

The chmod utility is packaged in coreutils across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:

Advertisement

Before running administrative tasks or automation scripts, verify whether chmod is installed and inspect which binary path and version your shell resolves:

type -a chmod
chmod --version 2>/dev/null || man -f chmod

# Illustrative output (reviewed against documentation)
chmod is /usr/bin/chmod
chmod (coreutils)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y coreutils

# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y coreutils

# Arch Linux
sudo pacman -S --noconfirm coreutils

# Alpine Linux
sudo apk add --no-cache coreutils

Command Syntax, Arguments, and Exit Status Codes

chmod [OPTION]... MODE[,MODE]... FILE... | chmod [OPTION]... OCTAL-MODE FILE...

The grammar of chmod accommodates two distinct specification formats: octal numbers and symbolic expressions. In octal mode, chmod OCTAL FILE... takes a 3-digit or 4-digit numeric mode (such as 644, 755, or 2775), where each digit represents the sum of Read (4), Write (2), and Execute (1). Octal mode sets an absolute, immutable target state across all permission bits.

In symbolic mode, chmod [ugoa...][+-=][rwxXst...] FILE... modifies permissions incrementally. The class selectors specify who to target: u (user/owner), g (group), o (others), or a (all). The operator defines the action: + (add), - (remove), or = (assign exact). The permission letters indicate which flags to modify: r (read), w (write), x (execute), X (conditional execute), s (SUID/SGID), and t (sticky bit).

  • 0 — All specified file modes were successfully modified.
  • 1 — Operational failure, such as encountering a file owned by another user without superuser privileges.
  • 2 — Malformed syntax, invalid mode argument, or unrecognized command-line flag.

Important Options and Flags Reference

Option / FlagLong Form / ArgumentTechnical Behavior and Purpose
-c--changesVerbose output that reports only when a file's permission mode is actually changed.
-v--verboseOutputs a diagnostic line for every file processed by chmod.
-f--silent, --quietSuppresses error messages for files that could not be modified due to permission constraints.
-R--recursiveRecursively changes file mode bits across directories and their subtrees.
--reference=RFILE--reference=RFILEUses reference file RFILE's mode instead of an explicit MODE value.
u+xSymbolic ModeAdds execute permission for the file owner only.
go-wSymbolic ModeRemoves write permission from group and other users.
a+rSymbolic ModeGrants read permission to user, group, and all other users.

The choice between octal numbers and symbolic notation should be guided by intent. Use octal notation (e.g. chmod 600 id_rsa) when establishing a strict, deterministic security baseline where you know the exact desired end state and want to overwrite any previous permissions.

Advertisement

Use symbolic notation (e.g. chmod +x deploy.sh or chmod g+w shared/) when making targeted, incremental adjustments. Symbolic operations leave all other mode bits intact, preventing unintended side effects such as accidentally stripping read permissions from group members when you only intended to grant execute rights to the owner.

When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.

Practical Basic and Advanced Usage Examples

1. Make a Shell Script Executable for the Owner

Add execute permission to a shell script so you can execute it directly from the terminal without invoking bash explicitly.

chmod u+x backup.sh
ls -l backup.sh

# Illustrative output (reviewed against documentation)
-rwxr--r-- 1 admin admin 1048 Oct 22 20:50 backup.sh

The symbolic modifier u+x adds the execute bit (x) strictly to the user (owner) class, leaving group and others as read-only.

2. Set Strict Read and Write Permissions for SSH Private Keys

Configure an SSH private key to mode 600 so that OpenSSH accepts it and prevents unauthorized local inspection.

chmod 600 ~/.ssh/id_ed25519
stat -c "%a %A %n" ~/.ssh/id_ed25519

# Illustrative output (reviewed against documentation)
600 -rw------- /home/admin/.ssh/id_ed25519

Mode 600 grants read/write to the owner and denies all access to group and world, complying with SSH security checks.

3. Apply Standard Web Directory Permissions (755)

Set a directory to mode 755 so that the owner has full control while web servers and visitors can browse files.

chmod 755 /var/www/html
stat -c "%a %A %n" /var/www/html

# Illustrative output (reviewed against documentation)
755 drwxr-xr-x /var/www/html

The owner receives rwx (7), while group and other receive r-x (5), enabling directory search and read access.

4. Configure Set Group ID (SGID) on a Shared Directory

Apply the SGID bit (2775) on a directory so that new files created inside inherit the directory's group ownership automatically.

sudo chmod 2775 /opt/shared_project
ls -ld /opt/shared_project

# Illustrative output (reviewed against documentation)
drwxrwsr-x 2 root developers 4096 Oct 22 20:52 /opt/shared_project

The 's' in the group execute column confirms the SGID bit (2000), ensuring group collaboration without manual chgrp calls.

5. Clone Permissions from a Reference File

Use the --reference flag to duplicate the exact permission mode of an existing production configuration file.

touch config_staging.env
chmod --reference=config_production.env config_staging.env
stat -c "%a %n" config_production.env config_staging.env

# Illustrative output (reviewed against documentation)
640 config_production.env
640 config_staging.env

The --reference option inspects config_production.env and applies its exact mode bits (640) to config_staging.env.

6. Audit Permission Changes in Real Time with -c

Run chmod with the -c (--changes) option to display output only when a file's mode is actually modified.

touch report.pdf && chmod 666 report.pdf
chmod -c 644 report.pdf

# Illustrative output (reviewed against documentation)
mode of 'report.pdf' changed from 0666 (rw-rw-rw-) to 0644 (rw-r--r--)

The -c flag provides clean, audited verification of the change without flooding scripts with redundant logs.

Real-World Workflows, Pipelines, and Shell Automation

Continuous Integration Artifact Hardening Pipeline

In a CI/CD build script, ensure that compiled application binaries receive execute permissions while credentials and environment files are strictly protected before packaging.

APP_DIR="/dist/app"
echo "Hardening build artifact permissions in $APP_DIR..."

# Grant execute rights to main application binary
chmod 755 "$APP_DIR/bin/server"

# Lock down private configuration and secrets
if [ -d "$APP_DIR/config" ]; then
  chmod 700 "$APP_DIR/config"
  chmod 600 "$APP_DIR/config"/*.env 2>/dev/null || true
fi

# Set standard read permissions on static web assets
if [ -d "$APP_DIR/public" ]; then
  find "$APP_DIR/public" -type d -exec chmod 755 {} +
  find "$APP_DIR/public" -type f -exec chmod 644 {} +
fi

echo "Artifact verification complete."

# Illustrative output (reviewed against documentation)
Hardening build artifact permissions in /dist/app...
Artifact verification complete.

This workflow applies principle-of-least-privilege permissions across application binaries, secret configurations, and static assets.

Collaborative Git Repository Directory Setup

Configure a bare git repository on a shared Linux server so multiple developers in the 'gitusers' group can push commits seamlessly.

REPO_PATH="/srv/git/project.git"
sudo mkdir -p "$REPO_PATH"
sudo chown -R git:gitusers "$REPO_PATH"

# Set SGID and group read/write recursively
sudo chmod -R 2775 "$REPO_PATH"

# Configure git sharedRepository setting
sudo git --git-dir="$REPO_PATH" config core.sharedRepository group

echo "Git shared repository configured at $REPO_PATH"
ls -ld "$REPO_PATH"

# Illustrative output (reviewed against documentation)
Git shared repository configured at /srv/git/project.git
drwxrwsr-x 2 git gitusers 4096 Oct 22 20:54 /srv/git/project.git

Setting SGID (2775) combined with git's core.sharedRepository setting ensures all pack files and ref updates created during git push inherit group write permissions.

Pipelines, Redirection, Quoting, and Shell Expansion

When embedding chmod inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.

Permissions, Security Implications, and Safe Execution

In Linux, only two entities have the privilege to change a file's mode: the user who owns the file and the root superuser (or processes possessing CAP_FOWNER). Even if a user has full write and execute access to a file via group or world permissions, they cannot alter its mode bits unless they own the file.

The Setuid (SUID) bit should be audited regularly with find / -perm /4000. If an attacker gains write access to a binary with SUID root, they can overwrite the executable to obtain permanent root access. Never set SUID permissions on shell scripts or untrusted programs.

GNU/Linux, BSD, and BusyBox Implementation Differences

The chmod utility is specified by POSIX.1-2017 and is standard across all Unix and Linux distributions. GNU coreutils chmod provides extra flags such as -c (--changes) and --reference, which are not defined by POSIX or present in traditional BSD implementations.

In minimal BusyBox environments, chmod supports standard octal and basic symbolic notation (e.g. +x), but lacks long options like --reference or --preserve-root. For maximum portability across Alpine and embedded systems, rely on standard octal and short symbolic flags.

Troubleshooting Common Errors and Diagnostics

chmod: changing permissions of 'file': Operation not permitted

Root Cause: You are attempting to modify a file that is owned by another user account, and you are not running as root.

Resolution: Verify file ownership with ls -l. If you are authorized to manage the file, run the command with sudo.

ls -l file.txt
sudo chmod 644 file.txt

chmod: cannot access 'file': No such file or directory

Root Cause: The file path was misspelled, does not exist, or points through a broken symbolic link.

Resolution: Check whether the target file exists using ls or test -e, and ensure relative paths are resolved correctly from the current directory.

ls -ld /path/to/file

chmod: invalid mode: '7777'

Root Cause: An invalid mode string was provided, or extra characters were included in the octal or symbolic specification.

Resolution: Ensure octal modes use valid 3-digit or 4-digit numbers (0000 to 7777, where 7777 includes SUID, SGID, and Sticky Bit), or verify symbolic syntax format.

chmod 755 file.sh

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
Use octal mode 600: chmod 600 filename. This grants read and write permissions to the owner while denying all access to group members and all other users on the system.
chmod alters the permission mode bits (read, write, execute) of a file or directory. chown alters the ownership (the user and group) of a file or directory.
chmod +x adds the execute permission bit to a file for user, group, and others. It is commonly used to make shell scripts, Python scripts, or compiled binaries executable directly from the command line.
No. On Linux, symbolic links always display lrwxrwxrwx permissions and their mode bits are never used by the kernel during access checks. The kernel always checks the permissions of the target file that the symlink points to.
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout