thumbnail

Contents

Basic Linux Commands

Contents

Bài viết này cung cấp hướng dẫn toàn diện về các lệnh Linux cơ bản dành cho người mới bắt đầu và những ai muốn củng cố kiến thức command line. Từ các lệnh đơn giản đến những thao tác phức tạp, bạn sẽ nắm vững cách sử dụng terminal Linux một cách hiệu quả.

50 lệnh Linux thiết yếu: Hướng dẫn chi tiết

Mục lục

  1. Giới thiệu
  2. File Management Commands
  3. Network Commands
  4. Process Management Commands
  5. User Management Commands
  6. File Transfer Commands
  7. Text Processing Commands
  8. System Commands
  9. Advanced Commands
  10. Troubleshooting
  11. FAQ

Giới thiệu

Bài viết này cung cấp hướng dẫn toàn diện về hơn 50 lệnh Linux thiết yếu mà mọi người dùng Linux cần biết. Từ cơ bản đến nâng cao, những lệnh này sẽ giúp bạn trở thành một Linux power user.

File Management Commands

1. ls - List Directory Contents

ls                    # Liệt kê file/thư mục trong thư mục hiện tại
ls -la                # Hiển thị chi tiết và file ẩn
ls -lh                # Hiển thị kích thước dễ đọc

2. cd - Change Directory

cd /path/to/directory    # Chuyển đến thư mục cụ thể
cd ..                    # Quay lại thư mục cha
cd ~                     # Về thư mục home
cd -                     # Quay lại thư mục trước đó

3. pwd - Print Working Directory

pwd                     # Hiển thị đường dẫn thư mục hiện tại

4. mkdir - Create Directory

mkdir new_directory     # Tạo thư mục mới
mkdir -p path/to/dir    # Tạo thư mục và các thư mục cha

5. rmdir - Remove Empty Directory

rmdir empty_directory   # Xóa thư mục rỗng

6. rm - Remove Files and Directories

rm file.txt            # Xóa file
rm -r directory        # Xóa thư mục và nội dung bên trong
rm -rf directory       # Xóa ép buộc không cần xác nhận
rm -i file.txt         # Xóa với xác nhận

7. touch - Create Empty File

touch new_file.txt     # Tạo file rỗng
touch file1 file2      # Tạo nhiều file cùng lúc

8. cp - Copy Files

cp file.txt /path/to/destination    # Sao chép file
cp -r directory /path/to/dest       # Sao chép thư mục
cp -i file.txt dest                 # Sao chép với xác nhận

9. mv - Move/Rename Files

mv file.txt /path/to/new_location   # Di chuyển file
mv old_name.txt new_name.txt        # Đổi tên file

10. cat - Display File Contents

cat file.txt           # Hiển thị toàn bộ nội dung file
cat file1 file2        # Hiển thị nhiều file
cat > file.txt         # Tạo file mới và nhập nội dung

11. nano/vim - Text Editors

nano file.txt          # Mở file với nano editor
vim file.txt           # Mở file với vim editor

12. find - Search Files

find . -name "file.txt"              # Tìm file theo tên
find /home -type f -name "*.txt"     # Tìm file .txt trong /home
find . -size +1M                     # Tìm file lớn hơn 1MB
find . -mtime -7                     # Tìm file thay đổi trong 7 ngày

13. grep - Search Text Patterns

grep "pattern" file.txt              # Tìm pattern trong file
grep -r "pattern" directory          # Tìm trong thư mục đệ quy
grep -i "pattern" file.txt           # Tìm không phân biệt hoa thường
grep -n "pattern" file.txt           # Hiển thị số dòng

14. tar - Archive Files

# Tạo archive
tar -cvf archive.tar file1 file2
tar -czvf archive.tar.gz directory

# Giải nén archive
tar -xvf archive.tar
tar -xzvf archive.tar.gz

15. df - Display Filesystem Usage

df                     # Hiển thị usage của filesystem
df -h                  # Hiển thị dạng dễ đọc

16. du - Directory Usage

du -sh directory       # Hiển thị kích thước thư mục
du -h --max-depth=1    # Hiển thị kích thước cấp 1

17. chmod - Change Permissions

chmod 755 file.txt     # Đặt quyền rwxr-xr-x
chmod +x script.sh     # Thêm quyền thực thi
chmod -w file.txt      # Xóa quyền ghi

18. chown - Change Ownership

chown user:group file.txt    # Đổi chủ sở hữu
chown -R user:group dir      # Đổi đệ quy cho thư mục

19. mount/umount - Mount Filesystems

mount /dev/sdb1 /mnt         # Mount device
umount /mnt                  # Unmount device

Network Commands

20. ping - Test Connectivity

ping google.com              # Test kết nối
ping -c 4 google.com         # Ping 4 lần rồi dừng

21. ifconfig/ip - Network Interface Info

ifconfig                    # Hiển thị network interfaces
ip a                        # Hiển thị địa chỉ IP (modern)
ip route                    # Hiển thị routing table

22. netstat/ss - Network Connections

netstat -tuln               # Hiển thị listening ports
ss -tuln                    # Modern version của netstat
netstat -an | grep :80      # Kiểm tra port 80

23. wget - Download Files

wget http://example.com/file.zip     # Download file
wget -c url                          # Resume download
wget -r http://example.com           # Recursive download

24. curl - Transfer Data

curl -O http://example.com/file.zip  # Download file
curl -I http://example.com           # Get headers only
curl -X POST -d "data" url           # POST request

25. nc (Netcat) - Network Utility

nc -zv 192.168.1.1 80       # Test port connectivity
nc -l 1234                  # Listen on port 1234

26. tcpdump - Packet Capture

tcpdump -i eth0             # Capture packets on eth0
tcpdump host 192.168.1.1    # Capture packets from/to host

27. iptables - Firewall Rules

iptables -L                 # List current rules
iptables -A INPUT -p tcp --dport 22 -j ACCEPT  # Allow SSH

28. traceroute - Trace Network Path

traceroute example.com      # Trace route to destination

29. nslookup - DNS Lookup

nslookup example.com        # DNS lookup
nslookup 8.8.8.8            # Reverse DNS lookup

30. ssh - Secure Shell

ssh user@hostname                   # Connect to remote host
ssh -p 2222 user@host               # Connect on custom port
ssh -L 8080:localhost:80 user@host  # Port forwarding

Process Management Commands

31. ps - Show Processes

ps aux                      # Show all processes
ps -ef                      # Show all processes (different format)
ps -p PID                   # Show specific process

32. top - Dynamic Process Viewer

top                         # Show running processes
top -u username             # Show processes for user

33. htop - Enhanced Process Viewer

htop                        # Enhanced version of top

34. kill - Terminate Process

kill PID                    # Terminate process by PID
kill -9 PID                 # Force kill process
kill -TERM PID              # Graceful termination

35. killall - Kill by Process Name

killall process_name        # Kill all processes with name
killall -9 process_name     # Force kill by name

36. uptime - System Uptime

uptime                      # Show system uptime and load

37. whoami - Current User

whoami                      # Show current username

38. env - Environment Variables

env                         # Show all environment variables
echo $PATH                  # Show specific variable

39. strace - Trace System Calls

strace -p PID              # Trace system calls of process
strace command             # Trace command execution

40. systemctl - Manage Services

systemctl status service   # Check service status
systemctl start service    # Start service
systemctl stop service     # Stop service
systemctl restart service  # Restart service
systemctl enable service   # Enable service at boot

41. journalctl - View System Logs

journalctl -xe             # Show recent log entries
journalctl -u service      # Show logs for specific service
journalctl -f              # Follow logs in real-time

42. free - Memory Usage

free -h                    # Show memory usage (human readable)
free -m                    # Show memory usage in MB

43. vmstat - Virtual Memory Statistics

vmstat 1                   # Show stats every second
vmstat 1 5                 # Show stats 5 times, 1 second apart

44. iostat - I/O Statistics

iostat                     # Show I/O statistics
iostat -x 1                # Extended stats every second

45. lsof - List Open Files

lsof                       # List all open files
lsof -p PID                # Show files opened by process
lsof -i :80                # Show processes using port 80

46. dmesg - Kernel Messages

dmesg                      # Show kernel ring buffer
dmesg | tail               # Show recent kernel messages

User Management Commands

47. passwd - Change Password

passwd                     # Change current user password
passwd username            # Change password for user

48. adduser/useradd - Add User

adduser username           # Add new user (interactive)
useradd username           # Add new user (non-interactive)

49. deluser/userdel - Delete User

deluser username           # Delete user
userdel -r username        # Delete user and home directory

50. usermod - Modify User

usermod -aG group username # Add user to group
usermod -s /bin/bash user  # Change user shell

51. groups - Show Group Memberships

groups username            # Show groups for user
groups                     # Show groups for current user

52. sudo - Execute as Root

sudo command               # Execute command as root
sudo -u user command       # Execute as different user
sudo -l                    # List sudo privileges

53. chage - Password Expiry

chage -l username          # Show password expiry info
chage -M 90 username       # Set password to expire in 90 days

54. id - User Identity

id                        # Show current user ID and groups
id username               # Show user ID and groups for user

55. newgrp - Change Group

newgrp groupname          # Switch to new group

File Transfer Commands

56. scp - Secure Copy

scp file user@host:/path           # Copy file to remote host
scp user@host:/path/file .         # Copy file from remote host
scp -r directory user@host:/path   # Copy directory recursively

57. rsync - Synchronize Files

rsync -avz source/ destination/    # Sync directories
rsync -avz file user@host:/path    # Sync to remote host
rsync --delete -avz src/ dest/     # Sync and delete extra files

58. ftp - File Transfer Protocol

ftp hostname               # Connect to FTP server

59. sftp - Secure FTP

sftp user@hostname         # Connect to SFTP server

Text Processing Commands

60. awk - Pattern Processing

awk '{print $1}' file.txt          # Print first column
awk -F: '{print $1}' /etc/passwd   # Use : as field separator

61. sed - Stream Editor

sed 's/old/new/g' file.txt         # Replace all occurrences
sed -i 's/old/new/g' file.txt      # Replace in-place

62. cut - Extract Columns

cut -d':' -f1 /etc/passwd          # Extract first field
cut -c1-10 file.txt                # Extract characters 1-10

63. sort - Sort Lines

sort file.txt                      # Sort lines alphabetically
sort -n file.txt                   # Sort numerically
sort -r file.txt                   # Sort in reverse order

64. wc - Word Count

wc file.txt                        # Count lines, words, characters
wc -l file.txt                     # Count lines only
wc -w file.txt                     # Count words only

65. paste - Merge Lines

paste file1.txt file2.txt          # Merge lines from files

66. join - Join Files

join file1.txt file2.txt           # Join files on common field

67. head - Show First Lines

head file.txt                      # Show first 10 lines
head -n 20 file.txt                # Show first 20 lines

68. tail - Show Last Lines

tail file.txt                      # Show last 10 lines
tail -n 20 file.txt                # Show last 20 lines
tail -f file.txt                   # Follow file (real-time)

System Commands

69. alias - Create Command Shortcuts

alias ll='ls -la'                  # Create alias
alias                              # List all aliases
unalias ll                         # Remove alias

70. history - Command History

history                           # Show command history
history | grep command            # Search history
!123                              # Execute command from history

71. clear - Clear Terminal

clear                             # Clear terminal screen

72. reboot - Restart System

reboot                            # Restart system
sudo reboot                       # Restart with sudo

73. shutdown - Power Off System

shutdown now                      # Shutdown immediately
shutdown -h +10                   # Shutdown in 10 minutes
shutdown -r now                   # Restart now

74. date - Show/Set Date

date                              # Show current date/time
date +%Y-%m-%d                    # Show date in specific format

75. echo - Display Text

echo "Hello World"                # Display text
echo $HOME                        # Display variable
echo "text" > file.txt            # Write to file
echo "text" >> file.txt           # Append to file

76. sleep - Delay Execution

sleep 5                           # Wait 5 seconds
sleep 1h                          # Wait 1 hour

77. time - Measure Execution Time

time ls                           # Measure time to execute ls

78. watch - Execute Command Repeatedly

watch -n 5 df -h                  # Execute every 5 seconds
watch 'ps aux | grep apache'      # Monitor Apache processes

Advanced Commands

79. uname - System Information

uname -a                          # Show all system info
uname -r                          # Show kernel version
uname -m                          # Show machine architecture

80. man - Manual Pages

man command                       # Show manual for command
man -k keyword                    # Search manual pages

81. less - Page Through Text

less file.txt                     # View file with paging
command | less                    # Page through command output
ln -s /path/to/file linkname      # Create symbolic link
ln /path/to/file linkname         # Create hard link

83. export - Set Environment Variables

export PATH=$PATH:/new/path       # Add to PATH
export VARIABLE=value             # Set environment variable

84. service - Manage Services

service ssh status                # Check SSH service status
service ssh start                 # Start SSH service
service ssh stop                  # Stop SSH service

85. diff - Compare Files

diff file1.txt file2.txt          # Compare two files
diff -u file1.txt file2.txt       # Unified diff format

86. comm - Compare Sorted Files

comm file1.txt file2.txt          # Compare sorted files

87. cmp - Compare Files Byte by Byte

cmp file1.txt file2.txt           # Compare files binary

88. whereis - Locate Command Files

whereis sudo                      # Find sudo binary and manual

89. whatis - Show Command Description

whatis sudo                       # Show brief description of sudo

90. dd - Low-level Copy

dd if=/dev/sda of=/dev/sdb               # Copy entire disk
dd if=/dev/zero of=file bs=1M count=100  # Create 100MB file

91. cal - Calendar

cal                               # Show current month calendar
cal 2024                          # Show year 2024 calendar
cal March 2024                    # Show specific month

92. zip/unzip - Archive Files

zip archive.zip file1 file2       # Create zip archive
zip -r name_file.zip folder/      # Nén toàn bộ cả thư mục và file con
unzip archive.zip                 # Extract zip archive

93. ufw - Uncomplicated Firewall

ufw enable                        # Enable firewall
ufw allow 22                      # Allow SSH port
ufw status                        # Show firewall status

Package Management Commands

94. apt (Ubuntu/Debian)

apt update                        # Update package list
apt upgrade                       # Upgrade packages
apt install package               # Install package
apt remove package                # Remove package
apt search keyword                # Search packages

95. yum (Red Hat/CentOS)

yum update                        # Update packages
yum install package               # Install package
yum remove package                # Remove package

96. pacman (Arch Linux)

pacman -S package                 # Install package
pacman -R package                 # Remove package
pacman -Syu                       # Update system

Troubleshooting

Common Issues and Solutions

1. Command Not Found Error

# Check if command exists
which command_name

# Install missing package
apt-get install package-name

# Add to PATH
export PATH=$PATH:/path/to/command

2. Permission Denied

# Use sudo for elevated privileges
sudo command_name

# Check file permissions
ls -la filename

# Change permissions
chmod +x filename

3. File Conflicts

# Use version control
git merge branch_name

# File locking
flock -x file -c "command"

# Atomic operations
mv temp_file target_file

4. Performance Issues

# Monitor system performance
top
htop
vmstat
iostat

# Check logs
tail -f /var/log/syslog

# Profile applications
gprof executable gmon.out

FAQ

Q: Những lệnh Linux được sử dụng phổ biến nhất là gì?

A: Các lệnh được sử dụng thường xuyên nhất bao gồm: cd, ls, mkdir, rm, cp, mv, echo, cat, grep, find, man, sudo, ssh, ping, df, du, free, top, ps, kill, and systemctl.

Q: Làm sao để liệt kê tất cả các lệnh có sẵn trong Linux?

A: Sử dụng lệnh compgen -c để hiển thị danh sách tất cả các lệnh có sẵn trên hệ thống của bạn.

Q: Làm sao để tìm một tập tin trong Linux?

A: Sử dụng lệnh find với cú pháp: find <đường_dẫn> -name “<tên_tập_tin>”. Ví dụ: find /home/user -name “example.txt”.

Q: Làm sao để dừng một tiến trình trong Linux?

A: Trước tiên hãy tìm ID của tiến trình bằng lệnh ps hoặc top, sau đó dùng kill PID, trong đó PID là ID của tiến trình. Ví dụ: kill 1234.

Q: Sự khác nhau giữa cp và mv là gì?

A: cp dùng để sao chép tập tin/thư mục (bản gốc vẫn còn), trong khi mv dùng để di chuyển hoặc đổi tên chúng (bản gốc bị xóa khỏi vị trí ban đầu).

Q: Làm sao để kiểm tra mức sử dụng bộ nhớ trong Linux?

A: Sử dụng lệnh free -h để hiển thị mức sử dụng bộ nhớ dưới dạng dễ đọc.


Kết luận

Bài viết này đã cung cấp hướng dẫn toàn diện về hơn 50 lệnh Linux thiết yếu. Việc thành thạo các lệnh này sẽ giúp bạn:

  • Quản lý file và thư mục hiệu quả
  • Kiểm soát các process và service
  • Cấu hình mạng và kết nối
  • Xử lý text và dữ liệu
  • Quản lý người dùng và phân quyền
  • Troubleshoot các vấn đề hệ thống

Hãy thực hành thường xuyên để trở thành một Linux power user!