Skip to content

Linux Basics

Mở đầu

Server world, Linux là protagonist tuyệt đối. >90% server toàn cầu chạy Linux, từ Zalo, Tiki đến Google search, sau đều Linux. Là dev, master Linux basics = must, không optional.

Bạn sẽ học:

  • File system: directory structure + philosophy "everything is file"
  • Commands: file op, text process, process management
  • Permissions: user, group, permission model
  • Shell basics: pipe, redirect, env var
  • Practical: log debug, process check, network diagnosis
ChươngNội dung
1File system
2Common commands
3Permission model
4Shell basics
5Practical scenarios

1. File system: everything is file

Linux core philosophy: everything is file. File thường = file, directory = file, disk = file, ngay cả network connection, process info = file. Unified abstraction này cho phép dùng cùng tool (read, write, permission) op gần như mọi system resource.

Linux 文件系统层级
点击目录查看用途说明
📁/根目录
⚙️/bin基础命令
📋/etc配置文件
🏠/home用户目录
📊/var可变数据
🗑️/tmp临时文件
📦/usr用户程序
🔍/proc进程信息
🔌/dev设备文件
/
整个文件系统的起点,所有目录和文件都从这里开始。Linux 中一切皆文件,所有设备、进程信息都以文件形式存在于这棵目录树中。

Directory structure

Tưởng filesystem Linux như cây ngược:

/                    ← Root (gốc)
├── home/            ← User home (file của bạn ở đây)
├── etc/             ← Config (system "setting panel")
├── var/             ← Data thay đổi (log, cache)
├── usr/             ← Software user install
├── tmp/             ← Temp file (restart mất)
├── proc/            ← Process info (virtual, không disk)
├── dev/             ← Device file (disk, terminal)
├── bin/             ← Basic commands (ls, cp, mv)
├── sbin/            ← Admin commands (cần root)
├── opt/             ← Third-party software
└── root/            ← root user home

Path

TypeFormatExampleNote
AbsoluteBắt đầu //home/hoang/code/app.jsTừ root, không ambiguous
RelativeTừ current dir./code/app.js hoặc ../config. = current, .. = parent

Power "everything is file"

CPU info? Read file: cat /proc/cpuinfo Memory usage? Read file: cat /proc/meminfo Random number? Read file: cat /dev/urandom Discard output? Write file: echo "no thanks" > /dev/null

Không cần API riêng, read/write file đủ. Unix philosophy elegance.


2. Common commands

Linux command format: command [options] [args]. Vd ls -la /home: ls command, -la option, /home arg.

Linux 命令速查
按分类查看常用命令及示例
ls列出文件和目录
ls -la /home
cd切换目录
cd /var/log
cp复制文件
cp -r src/ backup/
mv移动/重命名
mv old.txt new.txt
rm删除文件
rm -rf dist/
mkdir创建目录
mkdir -p src/components
find查找文件
find . -name "*.js" -type f

Top 10 most-used

CommandUseMemory
lsList filelist
cdSwitch directorychange directory
catView fileconcatenate
grepSearch textglobal regex print
findFind filefind
psView processprocess status
tail -fLive log-f = follow
chmodChange permissionchange mode
curlHTTP requestclient URL
sshRemote loginsecure shell

Art of command combination

Linux mạnh không ở single command, mà ở combine. Qua pipe |:

bash
# Top 5 process CPU
ps aux --sort=-%cpu | head -6

# Stats most frequent error type trong log
grep "ERROR" app.log | awk '{print $4}' | sort | uniq -c | sort -rn | head -10

# Find file >100MB
find / -size +100M -type f 2>/dev/null

# Monitor live log highlight error
tail -f /var/log/app.log | grep --color "ERROR"

Unix philosophy

"Do one thing well." Mỗi command 1 function, combine qua pipe → complex op. Đây là sao Linux command ngắn — chúng là lego, không phải Swiss army knife.


3. Permission model

Linux multi-user, permission = security foundation. Mỗi file có 3 group permission: Owner, Group, Others.

Đọc ls -l

bash
$ ls -l app.js
-rwxr-xr-- 1 hoang dev 2048 Jan 15 10:30 app.js
│├──┤├──┤├──┤
      └── File size
     └── Group
     └── Owner
   └── Others: r-- (read only)
   └── Group: r-x (read + execute)
 └── Owner: rwx (read + write + execute)
└── Type: - file, d dir, l link

3 permission ops

PermissionLetterNumberCho fileCho dir
Readr4View contentList content (ls)
Writew2Modify contentCreate/delete file trong dir
Executex1Run program/scriptEnter dir (cd)
Linux 权限解读器
输入权限字符串或数字,查看含义
-rwxr-xr-x
所有者(Owner)
所属组(Group)
其他人(Others)
常见权限组合
644普通文件(owner 读写,其他只读)
755可执行文件/目录(owner 全权限)
600私密文件(仅 owner 读写)
777完全开放(不推荐)

Numeric permission

3 số = Owner/Group/Others, mỗi số = r(4) + w(2) + x(1):

chmod 755 script.sh
  7 = rwx (4+2+1)  → Owner: read + write + execute
  5 = r-x (4+0+1)  → Group: read + execute
  5 = r-x (4+0+1)  → Others: read + execute
CommonMeaningUse
644rw-r--r--File thường (owner write, others read)
755rwxr-xr-xExecutable / directory
600rw-------Private file (SSH key)
777rwxrwxrwxMọi người read/write/execute (nguy hiểm)

sudo: tạm root

User thường permission hạn chế, 1 số op cần root. sudo:

bash
# User thường không sửa system config
$ vim /etc/nginx/nginx.conf
# Permission denied

# sudo tạm:
$ sudo vim /etc/nginx/nginx.conf

# Switch root (cẩn thận):
$ sudo su -

Minimum permission principle

Đừng chmod 777 để giải permission issue, = tháo cửa. Hãy xác định ai cần permission nào, grant chính xác. Tương tự, đừng long-term root, chỉ sudo khi cần.


4. Shell basics

Shell = "translator" giữa bạn + Linux kernel. Bash (default Linux) + Zsh (default macOS) phổ biến nhất.

Pipe + redirect

2 feature mạnh nhất Shell:

SymbolNameUseExample
``PipeOutput trước → input sau
>Output redirectWrite file (overwrite)echo "hello" > file.txt
>>AppendAppend cuối fileecho "world" >> file.txt
<Input redirectRead từ filewc -l < file.txt
2>Error redirectError vào filecmd 2> error.log
2>&1Merge outputError + normal mergecmd > all.log 2>&1

Environment variables

bash
# View hết
env

# View 1 var
echo $PATH
echo $HOME

# Set tạm (chỉ current shell)
export API_KEY="abc123"

# Set permanent (write config file)
echo 'export API_KEY="abc123"' >> ~/.bashrc
source ~/.bashrc   # Apply
CommonMeaningExample
$PATHCommand search path/usr/local/bin:/usr/bin:/bin
$HOMEUser home/home/hoang
$USERCurrent usernamehoang
$PWDCurrent dir/var/log
$SHELLCurrent shell/bin/bash

Shell script

Multi command vào file → script:

bash
#!/bin/bash
# deploy.sh

APP_DIR="/opt/myapp"
LOG_FILE="/var/log/deploy.log"

echo "$(date) - Starting deploy..." >> $LOG_FILE

# Pull latest
cd $APP_DIR && git pull origin main

# Install deps
npm install --production

# Restart service
pm2 restart myapp

echo "$(date) - Deploy done" >> $LOG_FILE
bash
chmod +x deploy.sh
./deploy.sh

Debug script

Đầu script set -ex: -e script gặp error thoát ngay, -x print mỗi command execute. Standard cho production script.


5. Practical scenarios

5.1 Log debug

Service issue → reflex đầu tiên: xem log.

bash
# 1. Live tracking (hay dùng nhất)
tail -f /var/log/app/error.log

# 2. Search time range error
grep "2024-01-15 14:" error.log | grep "ERROR"

# 3. Stats error/hour
grep "ERROR" app.log | awk '{print substr($1,1,13)}' | uniq -c

# 4. Last 100 lines
tail -100 app.log

# 5. Search multiple file
grep -r "OutOfMemory" /var/log/app/

5.2 Process check

App freeze, CPU spike, memory leak — từ process:

bash
# CPU top
ps aux --sort=-%cpu | head -10

# Memory top
ps aux --sort=-%mem | head -10

# Find specific
ps aux | grep "node"

# Detail (kèm thread)
top -Hp <PID>

# Files opened by process
lsof -p <PID>

# Graceful terminate (SIGTERM)
kill <PID>

# Force kill (SIGKILL, last resort)
kill -9 <PID>

5.3 Network diagnosis

Service connect không được? Network hay app?

bash
# Ping target
ping -c 4 google.com

# Check port open
telnet db-server 3306
# Hoặc nc
nc -zv db-server 3306

# Port machine listening
ss -tlnp
# Hoặc
netstat -tlnp

# DNS resolve
dig api.example.com
nslookup api.example.com

# Test HTTP
curl -v http://localhost:3000/health

# Network connection stats
ss -s

5.4 Disk space

Disk full = fault prod common nhất:

bash
# Partition usage
df -h

# Find biggest dir
du -sh /* 2>/dev/null | sort -rh | head -10

# Drill down
du -sh /var/log/* | sort -rh | head -10

# Find big file (>100MB)
find / -type f -size +100M 2>/dev/null | head -20

# Cleanup
# Old log
sudo journalctl --vacuum-size=500M
# Docker
docker system prune -a

Prod debug formula

"Log first, process second, network third, disk fourth". 90% prod issue locate được qua 4 step. Habit này = efficiency tăng vọt.


Tổng kết

Linux = must skill cho dev. Master basics = handle đa số daily dev + ops.

  1. Everything is file: Linux dùng file abstract unify access hardware, process, network
  2. Command combo: single command đơn giản, qua pipe | mới power thật
  3. Permission: Owner/Group/Others × R/W/E, dùng số (755) set nhanh
  4. Shell basics: pipe, redirect, env var, script = automation foundation
  5. Debug practice: log → process → network → disk

2026 cho VN dev

  • Distro:
    • Ubuntu: phổ biến nhất, easy
    • Debian: stable, server
    • Alpine: lightweight, container
    • Rocky/Alma Linux: thay CentOS legacy
  • VN context:
    • VPS giá rẻ VN: BKHost, Vietnix, AzDigi
    • International: DigitalOcean, Vultr, Hetzner
  • Modern tools 2026:
    • bat: thay cat, syntax highlight
    • fd: thay find, faster + simple
    • ripgrep (rg): thay grep, faster
    • eza: thay ls, color + icon
    • fzf: fuzzy finder magic
    • zoxide: smart cd
  • WSL2: Linux trên Windows, mainstream cho VN dev

Tài liệu