- Published on
Basic Terminal Commands: sudo, chmod, and chown
- Authors
- Name
- Hieu Cao
Introduction
Managing permissions and privileges is a crucial aspect of working in a Unix-based system. Three essential commands—sudo
, chmod
, and chown
—allow users to execute tasks with elevated privileges, modify file permissions, and change ownership. This guide introduces these commands, their options, and practical examples.
sudo
Command: Execute Commands as Superuser
The The sudo
command temporarily grants administrative privileges to execute commands that require elevated permissions.
Syntax
sudo [command]
Common Usage
Execute a Command as Superuser
sudo apt update
- Runs
apt update
with administrative privileges.
- Runs
Edit a Protected File
sudo nano /etc/hosts
- Opens the
hosts
file for editing with elevated privileges.
- Opens the
Switch to Superuser
sudo -i
- Opens a shell session with root privileges.
Note
- You may be prompted to enter your password when using
sudo
.
chmod
Command: Modify File Permissions
The The chmod
command changes the read, write, and execute permissions of a file or directory.
Syntax
chmod [options] mode file_name
Permission Basics
- r: Read (4)
- w: Write (2)
- x: Execute (1)
Common Usage
Grant Execute Permission
chmod +x script.sh
- Adds execute permission to
script.sh
.
- Adds execute permission to
Set Specific Permissions
chmod 644 file.txt
- Sets
file.txt
permissions to:- Owner: read and write
- Group: read-only
- Others: read-only
- Sets
Recursively Change Permissions
chmod -R 755 folder/
- Sets
folder
and its contents to:- Owner: read, write, and execute
- Group: read and execute
- Others: read and execute
- Sets
chown
Command: Change File Ownership
The The chown
command changes the owner and group of a file or directory.
Syntax
chown [options] owner[:group] file_name
Common Usage
Change File Owner
sudo chown username file.txt
- Changes the owner of
file.txt
tousername
.
- Changes the owner of
Change Owner and Group
sudo chown username:groupname file.txt
- Sets
username
as the owner andgroupname
as the group forfile.txt
.
- Sets
Recursively Change Ownership
sudo chown -R username:groupname folder/
- Changes the owner and group of
folder
and all its contents.
- Changes the owner and group of
Practical Example
Let’s combine these commands in a typical workflow:
Create a Script and Set Permissions
echo "#!/bin/bash echo 'Hello, World!'" > script.sh chmod +x script.sh
Run the Script with Elevated Privileges
sudo ./script.sh
Change Ownership of the Script
sudo chown username:groupname script.sh
Conclusion
Understanding and using sudo
, chmod
, and chown
commands effectively ensures secure and efficient management of files, directories, and system operations. Practice these commands to build confidence in handling permissions and privileges on Unix-based systems.