#!/bin/bash
set -euo pipefail
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m'
check_git_installed() {
if command -v git &> /dev/null; then
return 0
else
return 1
fi
}
check_and_install_homebrew() {
if ! command -v brew &> /dev/null; then
echo -e "${YELLOW}Homebrew not installed, starting Homebrew installation...${NC}"
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
if [ -f "/opt/homebrew/bin/brew" ]; then
eval "$(/opt/homebrew/bin/brew shellenv)"
elif [ -f "/usr/local/bin/brew" ]; then
eval "$(/usr/local/bin/brew shellenv)"
fi
fi
}
install_git() {
echo -e "${YELLOW}\nStarting Git installation via Homebrew...${NC}"
check_and_install_homebrew
brew install git
}
verify_git() {
echo -e "${YELLOW}\nVerifying Git installation status...${NC}"
if check_git_installed; then
GIT_VERSION=$(git --version)
echo -e "${GREEN}✅ Git installation successful! Version information: ${GIT_VERSION}${NC}"
echo -e "${YELLOW}Testing Git core functionality (creating temporary repository)...${NC}"
TEMP_DIR=$(mktemp -d -t git-test-XXXXXX)
cd "$TEMP_DIR" || exit 1
git init -q > /dev/null 2>&1
touch test.txt
git add test.txt > /dev/null 2>&1
git commit -m "test commit" -q > /dev/null 2>&1
if git log --oneline | grep -q "test commit"; then
echo -e "${GREEN}✅ Git functionality test passed!${NC}"
else
echo -e "${YELLOW}⚠️ Git is installed but functionality test abnormal (possible permission issue)${NC}"
fi
cd - > /dev/null 2>&1
rm -rf "$TEMP_DIR"
else
echo -e "${RED}❌ Git installation failed, please check manually!${NC}"
exit 1
fi
}
echo -e "${YELLOW}=== Starting Git installation status detection ===${NC}"
if check_git_installed; then
GIT_VERSION=$(git --version)
echo -e "${GREEN}Git is already installed, version information: ${GIT_VERSION}${NC}"
verify_git
else
echo -e "${RED}Git is not installed${NC}"
install_git
verify_git
fi
echo -e "\n${GREEN}=== Operation completed ===${NC}"
exit 0