1 特定分支
1.1?克隆指定分支(默認只下載該分支)
git clone -b <分支名> --single-branch <倉庫URL>
示例(克隆 某一個?分支):
git clone -b xxxxxx --single-branch xxxxxxx
-
-b
:指定分支 -
--single-branch
:僅克隆該分支(節省時間空間)
1.2?克隆后切換到另一個分支(如果已克隆倉庫)
如果已經克隆了倉庫,想切換到其他分支:
git fetch origin <分支名> # 先獲取分支信息
git checkout <分支名> # 切換到該分支
示例(切換到?lesson-2
):
git fetch origin lesson-2
git checkout lesson-2
2 所有分支
git clone xxx
git branch -r | grep -v '\->' | while read remote; do git branch --track "${remote#origin/}" "$remote"; done
git fetch --all
git pull --all
舉一反三:
比如我有一個需求:下載博主的教學源碼,就用到了git獲取分支的知識,具體需求是在克隆每一個分支的同時想對每一個分支都創建一個文件夾,又不會bash命令,就可以在ai的幫助下
?成功編寫一個sh文件完成我的需求:
#!/bin/bash
set -e # 任何命令失敗則退出
set -x # 打印執行的命令(調試模式)# 倉庫配置
REPO_URL="https://github.com/iamshaunjp/bootstrap-5-tutorial.git"
REPO_NAME="bootstrap-5-tutorial"
BRANCHES_DIR="../branches"# 1. 克隆倉庫(僅默認分支)
echo "步驟1/4: 克隆倉庫..."
if [ -d "$REPO_NAME" ]; thenecho "錯誤:目錄 $REPO_NAME 已存在,請刪除或重命名!"exit 1
fi
git clone "$REPO_URL" "$REPO_NAME" || {echo "克隆失敗!請檢查網絡或倉庫URL。"exit 1
}
cd "$REPO_NAME" || exit 1# 2. 獲取所有遠程分支
echo "步驟2/4: 獲取所有遠程分支..."
git fetch --all || {echo "獲取分支失敗!"exit 1
}# 3. 遍歷每個遠程分支并導出文件
echo "步驟3/4: 導出各分支到 $BRANCHES_DIR/..."
mkdir -p "$BRANCHES_DIR" || exit 1git branch -r | grep -v '\->' | while read -r remote; dobranch_name="${remote#origin/}"target_dir="$BRANCHES_DIR/$branch_name"echo "----------------------------------------"echo "正在處理分支: $branch_name"echo "目標目錄: $(pwd)/$target_dir"# 創建分支目錄mkdir -p "$target_dir" || {echo "創建目錄失敗: $target_dir"exit 1}# 切換到分支git checkout "$branch_name" 2>&1 | tee -a ../branch_log.txt || {echo "切換分支失敗: $branch_name"exit 1}# 復制文件(排除.git)echo "復制文件中..."cp -r ./* "$target_dir/" 2>&1 | tee -a ../copy_log.txt || {echo "復制文件失敗: $branch_name"exit 1}echo "完成: $branch_name -> $target_dir"echo "文件數量: $(ls -1 "$target_dir" | wc -l)"
done# 4. 最終檢查
echo "步驟4/4: 驗證導出結果..."
echo "----------------------------------------"
echo "所有分支已導出到: $(pwd)/$BRANCHES_DIR"
echo "分支列表:"
ls -1 "$BRANCHES_DIR"
echo "----------------------------------------"
echo "導出完成!"