Website Vidya
SecurityStep-by-Step Guide

chown Command in Linux: Change File & Directory Ownership

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

RR
Rajesh RayLead Systems Educator
Published:
12 min read
PDF Cheat Sheet
chown Command in Linux: Change File & Directory Ownership
AI Executive SummaryWebsiteVidya AI

12 min read

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

Key Highlights
  • What chown 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

Every file, directory, socket, and device node on a Linux system is governed by Discretionary Access Control (DAC), which relies on two primary identifiers stored in the filesystem inode: a user owner (UID) and a group owner (GID). Using the chown command in linux allows system administrators to reassign these ownership attributes so that web servers, database engines, container runtimes, and human users have appropriate access rights without resorting to insecure world-writable permissions.

Whenever files are uploaded by root during deployment, extracted from tar archives created on another build server, or migrated across attached storage volumes, mismatched ownership can cause permission denied failures in production services. Mastering chown syntax—including user-only, group-only, combined user:group specifications, and reference-based cloning—is critical for maintaining least-privilege security boundaries.

In this guide, we examine how chown interacts with the kernel Virtual File System (VFS) and NSS account databases, review its complete flag reference, walk through practical terminal examples, and cover vital security safeguards against symlink traversal and recursive root corruption.

Advertisement
chown Command in Linux: Change File & Directory Ownership — syntax, flags, and practical terminal workflow diagram
chown Command in Linux: Change File & Directory Ownership — command syntax, key options, and production workflow reference.

What chown Does and When to Use It

When you invoke chown, the binary first resolves symbolic user and group names into numeric 32-bit User IDs (UID) and Group IDs (GID) by querying the Name Service Switch (NSS) via getpwnam() and getgrnam() library calls (which read /etc/passwd, /etc/group, SSSD, or LDAP). Once resolved—or immediately if numeric IDs were supplied—chown invokes the Linux kernel fchownat(2) system call to update the st_uid and st_gid fields directly inside the target file's on-disk inode metadata.

When operating recursively with -R, GNU chown does not blindly follow paths using standard string concatenation; instead, it uses the gnulib fts (file tree stream) traversal engine combined with openat(2) and fchownat(2) directory file descriptors. This descriptor-relative traversal prevents time-of-check to time-of-use (TOCTOU) race conditions where a local attacker replaces a subdirectory with a symbolic link mid-traversal to trick a privileged process into taking ownership of /etc/shadow.

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 chown 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 chown 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 chown is installed and inspect which binary path and version your shell resolves:

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

# Illustrative output (reviewed against documentation)
chown is /usr/bin/chown
chown (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

chown [OPTION]... [OWNER][:[GROUP]] FILE...

The ownership specification argument [OWNER][:[GROUP]] supports four distinct syntactic patterns. Passing USER alone (e.g., chown alice app.log) changes only the user owner and leaves the group unchanged. Passing USER:GROUP (e.g., chown www-data:www-data /var/www) changes both the user and group owners. Passing USER: with a trailing colon but no group name (e.g., chown alice: report.csv) changes the user to alice and automatically sets the group to alice's primary login group as defined in /etc/passwd.

Finally, passing :GROUP with a leading colon and no user name (e.g., chown :developers /srv/repo) leaves the user owner untouched and modifies only the group owner, functioning identically to the chgrp utility. Note that historical UNIX documentation occasionally used a dot separator (USER.GROUP), but POSIX deprecated the dot because modern usernames frequently contain periods (such as firstname.lastname); always use a colon (:) as the separator.

  • 0 — All specified files and directories had their ownership updated (or verified) successfully.
  • 1 — Operational failure: permission denied (EPERM), nonexistent user/group spec, or missing target file (ENOENT).
  • 2 — Fatal command-line syntax error or unrecognized option flag.

Important Options and Flags Reference

Option / FlagLong Form / ArgumentTechnical Behavior and Purpose
-R--recursiveRecursively changes ownership of directories and all files and subdirectories contained within them.
-v--verboseOutputs a diagnostic status line for every single file processed, indicating whether ownership changed or remained the same.
-c--changesLike --verbose, but prints diagnostic output only for files whose user or group ownership actually changed.
-h--no-dereferenceModifies the ownership of symbolic links themselves rather than the target files they point to (default when -R is active).
-H(with -R)If a command-line argument is a symbolic link to a directory, traverses it while leaving internal tree symlinks unfollowed.
-L(with -R)Dereferences and traverses every symbolic link to a directory encountered during recursive tree walking (use with extreme caution).
--from--from=CURRENT_OWNER:CURRENT_GROUPChanges ownership of a file only if its current user and/or group match the specified filter criteria.
--reference--reference=RFILECopies the exact numeric UID and GID from an existing reference file RFILE instead of specifying OWNER:GROUP manually.
--preserve-root--preserve-rootRefuses to operate recursively on the root directory (/) to prevent catastrophic system-wide ownership corruption.

In production scripts and configuration management tasks, pairing -c (--changes) with -R (--recursive) provides an ideal audit log: rather than flooding your terminal or CI/CD log with tens of thousands of unchanged file lines (which -v produces), -c reports only the specific files whose ownership drifted from the desired state.

Advertisement

Understanding how chown treats symbolic links is equally vital. When run on a standalone symlink without -R, chown dereferences the link by default and changes the owner of the target file. Pass -h (--no-dereference) whenever you want to change the owner of the symlink inode itself. Conversely, when -R is active, chown defaults to -P (never follow directory symlinks) and does not follow symlinks unless you explicitly override it with -H or -L.

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. Change Both User and Group Owner of a Configuration File

Assign both the user owner and group owner of an Nginx virtual host configuration file to root:www-data and verify the updated inode metadata with ls -l.

sudo chown -c root:www-data /etc/nginx/conf.d/app.conf
ls -l /etc/nginx/conf.d/app.conf

# Illustrative output (reviewed against documentation)
changed ownership of '/etc/nginx/conf.d/app.conf' from root:root to root:www-data
-rw-r----- 1 root www-data 2048 Oct 22 14:15 /etc/nginx/conf.d/app.conf

Setting root as the user owner prevents the web server worker processes from modifying their own configuration file if compromised, while setting www-data as the group owner with 0640 permissions allows the workers to read it.

2. Recursively Change Ownership of a Web Application Directory

Use the -R and -c flags to assign ownership of an entire application release directory tree to the deploy user and www-data group.

sudo chown -Rc deploy:www-data /var/www/production-app

# Illustrative output (reviewed against documentation)
changed ownership of '/var/www/production-app/public/index.html' from root:root to deploy:www-data
changed ownership of '/var/www/production-app/storage/logs' from root:root to deploy:www-data
changed ownership of '/var/www/production-app' from root:root to deploy:www-data

The -R flag walks all nested subdirectories and files, while -c outputs only the paths that actually transitioned to deploy:www-data.

3. Change User and Automatically Adopt the User's Primary Group

Append a trailing colon after the username (USER:) to set the file owner to that user and simultaneously set the group owner to that user's primary login group.

sudo chown -v postgres: /var/lib/postgresql/16/main/pg_hba.conf
stat -c "%U:%G (%u:%g)" /var/lib/postgresql/16/main/pg_hba.conf

# Illustrative output (reviewed against documentation)
changed ownership of '/var/lib/postgresql/16/main/pg_hba.conf' from root:root to postgres:postgres
postgres:postgres (114:120)

Omitting the group name after the colon tells chown to look up the user's primary GID in /etc/passwd, preventing common mistakes where a sysadmin changes the user owner but accidentally leaves the file owned by the root group.

4. Change Only the Group Owner Using Leading Colon Syntax

Use a leading colon (:GROUP) to update the group ownership of a shared engineering directory without altering the existing user owner.

sudo chown -c :devops /opt/scripts/deploy.sh
ls -l /opt/scripts/deploy.sh

# Illustrative output (reviewed against documentation)
changed ownership of '/opt/scripts/deploy.sh' from alice:alice to alice:devops
-rwxr-x--- 1 alice devops 4120 Oct 22 09:30 /opt/scripts/deploy.sh

Running chown :devops is functionally identical to running chgrp devops, allowing you to standardize on a single utility across your shell scripts.

5. Conditionally Migrate Ownership Using the --from Filter

When deprovisioning a former contractor's account or fixing UID drift after an NFS migration, use --from to update only files currently owned by a specific user or UID.

sudo chown -Rc --from=1004:1004 developer:developer /srv/shared

# Illustrative output (reviewed against documentation)
changed ownership of '/srv/shared/docs/architecture.md' from 1004:1004 to developer:developer
changed ownership of '/srv/shared/scripts/sync.py' from 1004:1004 to developer:developer

The --from=1004:1004 guard acts as a safety precondition: files in /srv/shared owned by root, www-data, or other team members are untouched, while orphaned files owned by UID/GID 1004 are cleanly reassigned.

6. Clone Ownership from a Reference File and Handle Symbolic Links

Copy the exact UID and GID from an existing known-good file using --reference, and use -h to update a symbolic link itself without modifying its target.

sudo chown -c --reference=/etc/shadow /etc/gshadow
sudo chown -ch deploy:www-data /var/www/current

# Illustrative output (reviewed against documentation)
ownership of '/etc/gshadow' retained as root:shadow
changed ownership of '/var/www/current' from root:root to deploy:www-data

Without -h, running chown on a deployment symlink like /var/www/current would change the target directory it points to rather than the symlink inode itself.

Real-World Workflows, Pipelines, and Shell Automation

Safe Recursive Ownership Audit and Remediation for Container Volumes

When migrating persistent volumes between rootless containers or Kubernetes pods with securityContext.fsGroup changes, combine find and chown --from to audit and update only mismatched files while logging every change.

#!/usr/bin/env bash
set -euo pipefail

VOLUME_PATH="/var/lib/docker/volumes/postgres_data/_data"
OLD_UID="999"
NEW_OWNER="70:70"

echo "Auditing files owned by UID ${OLD_UID} in ${VOLUME_PATH}..."
MATCH_COUNT=$(sudo find "${VOLUME_PATH}" -uid "${OLD_UID}" | wc -l)
echo "Found ${MATCH_COUNT} items requiring UID migration."

if [ "${MATCH_COUNT}" -gt 0 ]; then
  sudo chown -Rc --preserve-root --from="${OLD_UID}" "+${NEW_OWNER}" "${VOLUME_PATH}"
fi

# Illustrative output (reviewed against documentation)
Auditing files owned by UID 999 in /var/lib/docker/volumes/postgres_data/_data...
Found 3 items requiring UID migration.
changed ownership of '/var/lib/docker/volumes/postgres_data/_data/PG_VERSION' from 999 to 70:70
changed ownership of '/var/lib/docker/volumes/postgres_data/_data/postgresql.conf' from 999 to 70:70
changed ownership of '/var/lib/docker/volumes/postgres_data/_data' from 999 to 70:70

Prefixing numeric IDs with a plus sign (+70:70) forces GNU chown to interpret the numbers directly as raw UID/GID integers without attempting an NSS name lookup in the host's /etc/passwd—essential when fixing container volume UIDs that only exist inside the container image.

Zero-Downtime Atomic Capistrano/Symlink Release Ownership Pipeline

In automated CI/CD deployment pipelines, set strict ownership on a newly extracted release folder and update the symlink itself with -h before reloading the service.

RELEASE_DIR="/var/www/releases/202610221800"
sudo chown -R root:www-data "${RELEASE_DIR}"
sudo chown -R www-data:www-data "${RELEASE_DIR}/storage" "${RELEASE_DIR}/bootstrap/cache"
sudo ln -sfn "${RELEASE_DIR}" /var/www/current
sudo chown -h root:www-data /var/www/current
ls -ld /var/www/current "${RELEASE_DIR}" "${RELEASE_DIR}/storage"

# Illustrative output (reviewed against documentation)
lrwxrwxrwx 1 root     www-data   31 Oct 22 18:00 /var/www/current -> /var/www/releases/202610221800
drwxr-xr-x 6 root     www-data 4096 Oct 22 18:00 /var/www/releases/202610221800
drwxrwxr-x 4 www-data www-data 4096 Oct 22 18:00 /var/www/releases/202610221800/storage

Separating code ownership (root:www-data, read-only for the web server) from writable runtime directories (www-data:www-data on storage/ and cache/) prevents remote code execution exploits from overwriting application source files.

Pipelines, Redirection, Quoting, and Shell Expansion

When embedding chown 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

Under Linux and POSIX security rules, only processes holding the CAP_CHOWN capability (ordinarily the root user) can change the user owner (UID) of a file. Standard unprivileged users cannot 'give away' ownership of their own files to another user because doing so would allow users to evade disk quota enforcement and plant setuid binaries or trojan files charged to another user's identity. Unprivileged users can only change the group owner of a file they own to another group of which they are already a member.

Crucially, as a kernel security hardening measure, changing the user or group owner of an executable file with chown automatically strips the setuid (S_ISUID, 4000) and setgid (S_ISGID, 2000) special permission bits unless specified otherwise by root on directories. If you intentionally maintain a setuid binary and run chown on it, you must re-apply the special permission bits afterward with chmod u+s.

GNU/Linux, BSD, and BusyBox Implementation Differences

While basic chown [-R] [-h] owner[:group] file syntax is standardized across POSIX.1-2017 systems, GNU coreutils (used on Debian, Ubuntu, RHEL, Fedora, and Arch) adds powerful extensions that do not exist on BSD or macOS: specifically --from, --reference, --preserve-root, and the +UID numeric bypass prefix.

On FreeBSD and macOS, if a numeric username exists in the directory service, chown prioritizes the username unless you manage IDs carefully, and neither --from nor --reference is supported (on macOS, you must query reference UID/GID with stat -f '%u:%g' ref_file and pass the result to chown). On Alpine Linux, BusyBox chown supports -R, -h, -c, -v, and -H/-L/-P, but lacks --from and --reference unless the coreutils package is installed.

Troubleshooting Common Errors and Diagnostics

chown: changing ownership of 'file': Operation not permitted

Root Cause: Either you ran chown as a non-root user without CAP_CHOWN, the file has the ext4/XFS immutable attribute (+i) enabled, or the file resides on a network filesystem (NFS with root_squash) or non-POSIX filesystem (FAT32/exFAT).

Resolution: Run the command with sudo, check for the immutable flag using lsattr file (and clear it with sudo chattr -i file if set), or check mount options with findmnt if on NFS or VFAT.

lsattr /etc/resolv.conf
sudo chattr -i /etc/resolv.conf
sudo chown root:root /etc/resolv.conf

chown: invalid user: 'www-data:www-data' on RHEL or Rocky Linux

Root Cause: Different Linux distributions use different default service account names (Debian/Ubuntu use www-data for web servers, whereas RHEL/Rocky/AlmaLinux use nginx or apache).

Resolution: Verify the exact service user and group names in /etc/passwd and /etc/group using getent before running chown.

getent passwd nginx apache www-data
sudo chown -R nginx:nginx /usr/share/nginx/html

Setuid or Setgid bit disappeared after running chown

Root Cause: The Linux kernel's fchownat() syscall automatically clears S_ISUID and S_ISGID bits on regular executable files when ownership changes to prevent privilege escalation.

Resolution: Always run chown first and apply special chmod permission modes (such as 4755 or u+s) second.

sudo chown root:admin /usr/local/bin/custom-helper
sudo chmod 4750 /usr/local/bin/custom-helper

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
The chown command changes who owns a file or directory (the User ID and Group ID stored in the inode), whereas the chmod command changes what actions those owners and others are allowed to perform (the read, write, execute, setuid, setgid, and sticky permission bits). In practice, you use chown to assign the right owner and group, and chmod to enforce the least-privilege access mask.
Pass a colon immediately followed by the group name with no username before the colon: sudo chown :developers filename. This leaves the current user owner unchanged and updates only the group owner, behaving identically to chgrp developers filename.
Filesystems such as FAT32, exFAT, and default NTFS mounts do not store native POSIX per-inode UID and GID fields on disk. Instead, the Linux kernel emulates ownership for the entire volume at mount time. To change the owner of files on a FAT32 or exFAT volume, pass the uid=1000,gid=1000 options to the mount command or in /etc/fstab.
By default, no. When you run chown -R, it operates in physical mode (-P): it changes the ownership of the symbolic links themselves and does not follow symlinks that point to external directories. This default protects you from accidentally changing ownership of system directories linked inside a user folder.
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