The chown
command in Linux changes the ownership of files and directories. It’s essential for managing permissions, especially in multi-user environments or when transferring files between users. Below are practical examples to master chown
:
Change Ownership of a File
chown user1 file.txt
Changes the owner of file.txt
to user1
.
Change Ownership of a Directory
chown user1 /path/to/directory
Changes the owner of the directory to user1
.
Change Ownership and Group Simultaneously
chown user1:group1 file.txt
- Sets the owner to
user1
and the group togroup1
.
Change Group Ownership Only
chown :group1 file.txt
Changes the group of file.txt
to group1
(owner remains unchanged).
Recursively Change Ownership of a Directory
chown -R user1 /path/to/directory
-R
: Recursively changes ownership for all files and subdirectories.
Change Ownership Using a Reference File
chown --reference=ref_file.txt target_file.txt
Sets the ownership of target_file.txt
to match ref_file.txt
.
Change Ownership for Symbolic Links
chown -h user1 symlink
-h
: Changes ownership of the symbolic link itself, not the target file.
Change Ownership and Suppress Errors
chown -f user1 file.txt
-f
: Suppresses error messages (e.g., for inaccessible files).
Change Ownership with Verbose Output
chown -v user1 file.txt
-v
: Displays a message for each file processed.
Change Ownership for All Files in a Directory
chown user1 *
Changes ownership of all files in the current directory to user1
.
Change Ownership for Specific File Types
chown user1 *.txt
Changes ownership of all .txt
files in the current directory.
Change Ownership and Preserve Root
chown --preserve-root -R user1 /
--preserve-root
: Prevents recursive ownership changes on the root directory.
Change Ownership for a Specific User and Group by UID/GID
chown 1001:1002 file.txt
1001
: User ID (UID).1002
: Group ID (GID).
Change Ownership for Files Matching a Pattern
find /path/to/dir -name "*.log" -exec chown user1 {} \;
find
: Locates.log
files and changes their ownership touser1
.
Key Notes:
- Permissions: Only the root user or the file owner can change ownership.
- Recursive Changes: Use
-R
carefully to avoid unintended ownership changes. - Symbolic Links: Use
-h
to modify the link itself, not the target.