Zsh一站式初始化脚本
这份脚本适合做一轮最常用的 Zsh 环境初始化:
- 安装
Oh My Zsh - 安装
zsh-autosuggestions - 安装
zsh-syntax-highlighting - 修改主题和插件配置
脚本
#!/bin/zsh
retry_command() {
local cmd="$1"
local retries=3
local count=0
while ((count < retries)); do
eval "$cmd" && return 0
count=$((count + 1))
echo "Attempt $count/$retries failed. Retrying..."
sleep 2
done
echo "Command failed after $retries attempts: $cmd"
exit 1
}
detect_os() {
if [[ "$OSTYPE" == "darwin"* ]]; then
echo "macos"
elif [[ "$OSTYPE" == "linux-gnu"* ]]; then
echo "linux"
else
echo "unknown"
fi
}
main() {
retry_command 'RUNZSH=no sh -c "$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"'
retry_command 'git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions'
retry_command 'git clone https://github.com/zsh-users/zsh-syntax-highlighting.git ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting'
local os_type=$(detect_os)
if [[ "$os_type" == "macos" ]]; then
sed -i '' -e 's/ZSH_THEME="robbyrussell"/ZSH_THEME="ys"/g' \
-e 's/plugins=(git)/plugins=(z sudo git zsh-autosuggestions zsh-syntax-highlighting)/g' \
"$HOME/.zshrc"
else
sed -i -e 's/ZSH_THEME="robbyrussell"/ZSH_THEME="ys"/g' \
-e 's/plugins=(git)/plugins=(z sudo git zsh-autosuggestions zsh-syntax-highlighting)/g' \
"$HOME/.zshrc"
fi
}
main注意
这份脚本默认 ~/.zshrc 里已有 Oh My Zsh 默认生成的那一行 plugins=(git),否则替换命令不会命中。