PlusMagi's Blog By Pitt Phunsanit Git,Shell Script GIT: ดู Repository, Branch, Status ด้วย Shell Script

GIT: ดู Repository, Branch, Status ด้วย Shell Script

ในบทความนี้ เราจะสร้าง Shell Script ที่ช่วยให้คุณตรวจสอบสถานะของ Repository, Branch และไฟล์ที่มีการเปลี่ยนแปลงใน Workspace ที่มีหลาย Repository อยู่ภายใน ซึ่งรวมถึงการจัดการไฟล์ที่ถูกลบหรือเพิ่มเข้าไปด้วย

ขั้นตอนการสร้าง Shell Script

  1. เปลี่ยนไปที่ Workspace ที่เก็บ Git folder ไว้ เช่น
    cd /Users/Shared/Gits/phunsanit
  2. สร้างไฟล์
    touch git-status-all.sh
  3. ให้สิทธิ์ให้ไฟล์สามารถรันได้
    chmod +x git-status-all.sh
  4. เปิดไฟล์มาแก้ไข
    nano git-status-all.sh
  5. ใส่เนื้อหาตามตัวอย่างด้านล่าง

git-status-all.sh

BASH / Shell

#!/bin/bash

current_root=$(pwd)

for dir in */; do
	if [ -d "$dir/.git" ]; then
		changes=$(cd "$dir" && git status --porcelain)
		if [ -n "$changes" ]; then
			branch=$(cd "$dir" && git branch --show-current)
			if [ -z "$branch" ]; then branch="(Detached HEAD)"; fi
			repo_full_path="${current_root}/${dir%/}"
			echo "=========================================="
			printf "# %-16s cd "%s"
" "Path:" "$repo_full_path"
			printf "# %-16s %s
" "Git Repository:" "$dir"
			printf "# %-16s %s
" "Branch:" "$branch"
			echo "$changes" | while read -r line; do
				status="${line:0:2}"
				file="${line:3}"
				file=$(echo "$file" | sed 's/^"//;s/"$//')
				fullpath="$file"
				if [[ "$status" == *"D"* ]]; then
					echo "git rm "$fullpath""
				else
					echo "git add "$fullpath""
				fi
			done
		fi
	fi
done

การใช้งาน Shell Script

หลังจากสร้างและแก้ไขไฟล์ Shell Script แล้ว คุณสามารถรันไฟล์นี้ได้โดยใช้คำสั่ง
./git-status-all.sh

บทสรุป

Shell Script ที่สร้างขึ้นนี้ช่วยให้คุณสามารถตรวจสอบสถานะของ Repository, Branch และไฟล์ที่มีการเปลี่ยนแปลงใน Workspace ที่มีหลาย Repository อยู่ภายใน รวมถึงการจัดการไฟล์ที่ถูกลบหรือเพิ่มเข้าไปด้วย ทำให้การจัดการ Git ใน Workspace ที่มีหลาย Repository ง่ายขึ้น