The chmod (change mode) command in Linux is used to modify file or directory permissions. Permissions control who can read, write, or execute a file, and are set for the owner, group, and others. Below are 10 detailed examples demonstrating the use of chmod with both symbolic and numeric (octal) notations.
Sets permissions so only the file owner can read, write, and execute the file.
chmod 700 file.txt
Explanation: 700 means owner gets all permissions (read=4, write=2, execute=1; 4+2+1=7), while group and others get no permissions (0).
Allows the owner and group to read and write to the file, with no permissions for others.
chmod u=rw,g=rw,o= file.txt
Explanation: u=rw sets read and write for the user (owner), g=rw for the group, and o= removes all permissions for others.
Sets a script to be readable and executable by everyone.
chmod 755 script.sh
Explanation: 755 gives the owner full permissions (7=read+write+execute) and group/others read and execute permissions (5=read+execute).
Adds execute permission to the owner without altering other permissions.
chmod u+x file.txt
Explanation: u+x adds execute permission (x) to the user (owner) while keeping group and others' permissions unchanged.
Removes write permission for the group while leaving other permissions intact.
chmod g-w file.txt
Explanation: g-w removes write permission (w) from the group.
Makes a file readable by owner, group, and others, with no write or execute permissions.
chmod 444 file.txt
Explanation: 444 assigns read-only permission (4=read) to owner, group, and others.
Applies permissions to a directory and all its contents recursively.
chmod -R 755 my_folder
Explanation: -R applies 755 (owner: read/write/execute; group/others: read/execute) to my_folder and all files/subdirectories inside it.
Gives read, write, and execute permissions to owner, group, and others.
chmod 777 file.txt
Explanation: 777 grants full permissions (7=read+write+execute) to everyone. Use cautiously, as it allows anyone to modify or execute the file.
Sets a directory to allow the owner full access, group read-only, and no access for others.
chmod u=rwx,g=r,o= my_directory
Explanation: u=rwx gives the owner read, write, and execute; g=r gives the group read-only; o= removes all permissions for others.
Copies the permissions of one file to another file.
chmod --reference=source.txt target.txt
Explanation: The --reference option copies the permissions of source.txt to target.txt, ensuring identical permission settings.
Notes: Always verify permissions with ls -l after using chmod. Use numeric mode for precise control or symbolic mode for selective changes. Be cautious with permissions like 777 to avoid security risks.