在 post-commit 腳本中,可以使用 Shell 腳本的條件語句(if [ -z ... ])來檢查環境變數是否有值。
以下是針對 git commit 時,更新版本資訊的 .git/hooks/post-commit 腳本:
撰寫 post-commit 腳本
這個腳本會檢查 GIT_APP_ENV 是否存在。如果為空,就執行基礎指令;如果有值,則帶上 --env 參數。
Bash
#!/bin/sh
# 取得環境變數 (由 git commit 指令前置傳入)
TARGET_ENV=$GIT_APP_ENV
if [ -z "$TARGET_ENV" ]; then
# 情況 A: 沒傳入環境參數
echo "未偵測到環境參數,執行基礎版本更新..."
php artisan version:update
else
# 情況 B: 有傳入環境參數 (例如 test)
echo "偵測到環境參數: $TARGET_ENV,執行特定環境更新..."
php artisan version:update --env="$TARGET_ENV"
fi如何在終端機使用
現在可以根據需求靈活選擇 Commit 方式:
一般提交 (不帶環境參數)
Bash
git commit -m "feat: 修正備份邏輯"
# 這會觸發:php artisan version:update測試環境提交
Bash
GIT_APP_ENV=test git commit -m "feat: 測試新功能"
# 這會觸發:php artisan version:update --env=test正式環境提交
Bash
GIT_APP_ENV=production git commit -m "fix: 緊急修復"
# 這會觸發:php artisan version:update --env=production