Bỏ qua để đến nội dung

Headless Mode

Thời gian học: ~30 phút

Yêu cầu trước: Phase 10 (Team Collaboration)

Kết quả: Sau module này, bạn sẽ hiểu headless mode căn bản, biết cách script Claude Code, và sẵn sàng cho automation nâng cao.


Bạn muốn chạy Claude Code như một phần của script. Có thể là tự động generate test cho toàn bộ file trong thư mục. Có thể là code review tự động cho mọi PR. Có thể là batch process documentation. Nhưng Claude Code là interactive — nó chờ input của bạn, hiển thị spinner, yêu cầu approval.

Headless mode giải quyết vấn đề này: Claude thực thi, xuất kết quả, trả quyền điều khiển lại cho script của bạn. Không cần tương tác. Điều này mở ra automation: cron job, CI/CD pipeline, batch processing, và nhiều hơn nữa.


Khía cạnhInteractiveHeadless
Khởi chạyclaudeclaude -p "prompt"
Đầu vàoHội thoạiMột prompt duy nhất
Đầu raCó format, spinnerRaw stdout
ApprovalBắt buộcBỏ qua hoặc tự động
Use caseDevelopmentAutomation

Flag -p (print) là chìa khóa của headless mode:

Terminal window
claude -p "Prompt của bạn ở đây"
  • Thực thi prompt
  • Xuất kết quả ra stdout
  • Trả về shell khi hoàn tất
  • Exit code cho biết thành công/thất bại
Terminal window
# Lưu vào biến
result=$(claude -p "Giải thích function này")
# Ghi vào file
claude -p "Generate README" > README.md
# Pipe sang command khác
claude -p "List issues trong code" | grep "ERROR"
Terminal window
# Prompt trực tiếp
claude -p "Giải thích recursion"
# Với context từ file
claude -p "Review code này: $(cat file.js)"
# Pipe từ stdin ⚠️ Cần verify hỗ trợ
cat file.js | claude -p "Review code này"
  • 0: Thành công
  • Non-zero: Lỗi (check stderr)
  • Dùng trong script: if claude -p "..."; then ... fi

Scenario: Tự động hóa việc tạo documentation bằng headless Claude Code.

Terminal window
claude -p "2 + 2 bằng bao nhiêu?"

Output:

4

Kiểm tra exit code:

Terminal window
echo $?

Output:

0
Terminal window
explanation=$(claude -p "Giải thích async/await trong một đoạn văn")
echo "$explanation"

Output:

Async/await là tính năng JavaScript giúp code bất đồng bộ
dễ viết và dễ đọc hơn bằng cách cho phép bạn viết các thao tác
bất đồng bộ theo cú pháp trông như đồng bộ...
Terminal window
claude -p "Generate README.md cho một TypeScript utility library" > README.md
head -5 README.md

Output:

# TypeScript Utility Library
Một tập hợp các tiện ích TypeScript hữu ích cho các tác vụ phổ biến.
## Cài Đặt
generate-docs.sh
#!/bin/bash
for file in src/*.ts; do
echo "Đang document $file..."
doc=$(claude -p "Generate JSDoc comment cho: $(cat "$file")")
echo "$doc" > "docs/$(basename "$file" .ts).md"
done
echo "Documentation hoàn tất!"

Chạy script:

Terminal window
chmod +x generate-docs.sh
./generate-docs.sh

Output:

Đang document src/utils.ts...
Đang document src/helpers.ts...
Đang document src/api.ts...
Documentation hoàn tất!

Bước 5: Logic Điều Kiện Dựa Trên Output

Phần tiêu đề “Bước 5: Logic Điều Kiện Dựa Trên Output”
check-security.sh
#!/bin/bash
result=$(claude -p "Review code này để tìm lỗi bảo mật.
Output 'SAFE' nếu không có vấn đề, hoặc 'UNSAFE: [lý do]' nếu có vấn đề.
Code: $(cat "$1")")
if [[ "$result" == SAFE* ]]; then
echo "$1 passed security check"
exit 0
else
echo "$1 failed: $result"
exit 1
fi

Chạy script:

Terminal window
./check-security.sh src/app.js

Output (trường hợp an toàn):

✅ src/app.js passed security check

Output (trường hợp có vấn đề):

❌ src/app.js failed: UNSAFE: SQL injection vulnerability detected
Terminal window
if ! output=$(claude -p "Generate test cho $(cat file.js)" 2>&1); then
echo "Lỗi: $output"
exit 1
fi
echo "$output" > tests.js

Mục tiêu: Thực thi lệnh Claude headless đầu tiên của bạn.

Hướng dẫn:

  1. Chạy: claude -p "Nói xin chào"
  2. Capture vào biến: greeting=$(claude -p "Nói xin chào")
  3. Echo biến: echo "$greeting"
  4. Kiểm tra exit code: echo $?
💡 Gợi Ý

Output sẽ là một lời chào đơn giản. Exit code 0 nghĩa là thành công.

✅ Giải Pháp
Terminal window
claude -p "Nói xin chào"
# Output: Xin chào!
greeting=$(claude -p "Nói xin chào")
echo "$greeting"
# Output: Xin chào!
echo $?
# Output: 0 (thành công)

Mục tiêu: Generate code vào file.

Hướng dẫn:

  1. Generate function: claude -p "Viết JavaScript function để viết hoa chữ cái đầu" > capitalize.js
  2. Verify: cat capitalize.js
  3. Chạy: node -e "$(cat capitalize.js); console.log(capitalize('hello'))"
💡 Gợi Ý

Dùng redirect > để ghi output vào file. Dùng $(cat file) để đọc nội dung file làm input.

✅ Giải Pháp
Terminal window
claude -p "Viết JavaScript function tên capitalize nhận string và return với chữ cái đầu viết hoa" > capitalize.js
cat capitalize.js
node -e "$(cat capitalize.js); console.log(capitalize('hello'))"
# Output: Hello

Mục tiêu: Xử lý nhiều file bằng script.

Hướng dẫn:

  1. Tạo 3 file code nhỏ trong test directory
  2. Viết bash script loop qua các file
  3. Với mỗi file, generate mô tả một dòng
  4. Output tất cả mô tả vào summary.txt
💡 Gợi Ý

Dùng for file in directory/*.js để loop. Dùng >> để append vào summary file thay vì overwrite.

✅ Giải Pháp
Terminal window
# Tạo test file
mkdir -p test-batch
echo "function add(a, b) { return a + b; }" > test-batch/math.js
echo "const API_URL = 'https://api.example.com';" > test-batch/config.js
echo "class User { constructor(name) { this.name = name; } }" > test-batch/user.js
# Batch processing script (lưu thành batch-describe.sh)
#!/bin/bash
for file in test-batch/*.js; do
name=$(basename "$file")
desc=$(claude -p "Mô tả trong một dòng: $(cat "$file")")
echo "$name: $desc" >> test-batch/summary.txt
done
# Chạy và verify
chmod +x batch-describe.sh
./batch-describe.sh
cat test-batch/summary.txt

Terminal window
claude -p "prompt" # Thực thi và output
result=$(claude -p "prompt") # Capture vào biến
claude -p "prompt" > file.txt # Output vào file
claude -p "prompt" | grep "pattern" # Pipe sang command
Terminal window
claude -p "Review: $(cat file.js)" # Inline nội dung file
Terminal window
# Xử lý lỗi
if ! result=$(claude -p "..."); then
echo "Failed"
exit 1
fi
# Loop processing
for f in *.js; do
claude -p "Document: $(cat "$f")" > "${f%.js}.md"
done
CodeÝ Nghĩa
0Thành công
Non-zeroLỗi

Flag Quan Trọng ⚠️ Cần verify khả dụng

Phần tiêu đề “Flag Quan Trọng ⚠️ Cần verify khả dụng”
FlagMục Đích
-p "prompt"Thực thi headless
--helpHiển thị các tùy chọn có sẵn

❌ Sai Lầm✅ Cách Đúng
Mong đợi tính năng interactiveHeadless là one-shot. Không có conversation.
Prompt dài trực tiếp trong commandDùng biến hoặc file cho prompt dài
Bỏ qua exit codeLuôn check exit code trong script
Không escape ký tự đặc biệtQuote biến: "$(cat file)"
Giả định hành vi giống interactiveTest headless riêng. Output format khác.
Không xử lý lỗiCapture stderr, check exit code
Overload với file khổng lồContext limit vẫn áp dụng. Chia nhỏ file lớn.

Scenario: Một startup Việt Nam cần tạo API documentation cho 50+ endpoint. Quy trình thủ công mất 2 ngày cho mỗi lần update documentation.

Giải pháp với headless mode:

generate-api-docs.sh
#!/bin/bash
for endpoint in src/routes/*.ts; do
name=$(basename "$endpoint" .ts)
echo "Đang document $name..."
claude -p "Generate OpenAPI documentation cho endpoint này:
$(cat "$endpoint")
Output ở định dạng YAML." > "docs/api/$name.yaml"
done
# Gộp tất cả YAML file
claude -p "Gộp các OpenAPI spec này thành một:
$(cat docs/api/*.yaml)" > docs/openapi.yaml
echo "API documentation đã được tạo!"

Kết quả:

  • 2 ngày thủ công → 15 phút tự động
  • Chạy hàng đêm qua cron job
  • Documentation luôn up-to-date
  • Chỉ cần human review khi cần thiết

Quote: “Headless mode đã biến Claude từ chat buddy thành documentation factory.”


Phase Tiếp Theo: Module 11.2: SDK Integration