Skip to content

shell脚本

基础模版

shell
#!/bin/bash

set -euo pipefail
IFS=$'\n\t'

#输出颜色
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[0;33m'
NC='\033[0m' # 无颜色

#日志打印函数
error() {
    echo -e "${RED}错误: $1${NC}" >&2
    exit 1
}
warn() {
    echo -e "${YELLOW}警告: $1${NC}" >&2
}
success() {
    echo -e "${GREEN}$1${NC}"
}

#系统信息
gum_detect_os() {
    case "$(uname -s 2>/dev/null || true)" in
        Darwin) echo "Darwin" ;;
        Linux) echo "Linux" ;;
        *) echo "unsupported" ;;
    esac
}
gum_detect_arch() {
    case "$(uname -m 2>/dev/null || true)" in
        x86_64|amd64) echo "x86_64" ;;
        arm64|aarch64) echo "arm64" ;;
        i386|i686) echo "i386" ;;
        armv7l|armv7) echo "armv7" ;;
        armv6l|armv6) echo "armv6" ;;
        *) echo "unknown" ;;
    esac
}
os="$(gum_detect_os)"
arch="$(gum_detect_arch)"
  • set -euo pipefail
    • -e 一旦脚本中的某个命令返回非零退出状态(即失败),整个脚本会立即退出。默认情况下,Bash 脚本会忽略非零的退出状态继续执行,而 set -e 强制脚本在错误发生时终止。
    • -u 在脚本中引用未定义的变量时会立即报错并退出,而不是默默地将其视为空字符串。
    • -o pipefail 如果管道中的任何一个命令失败(返回非零退出状态),整个管道的退出状态会被视为失败。更准确地捕获管道中的错误。
  • 输出颜色
  • 日志打印函数

常用函数

shell
install_homebrew() {
    local brew_bin=""
    if [[ "$OS" == "macos" ]]; then
        brew_bin="$(resolve_brew_bin || true)"
        if [[ -z "$brew_bin" ]]; then
            if ! is_macos_admin_user; then
                print_homebrew_admin_fix
                exit 1
            fi
            ui_info "Homebrew not found, installing"
            # Use Tsinghua mirror for China
            if [[ "${USE_CN_MIRROR:-0}" == "1" ]] || is_mainland_china; then
                ui_info "Using Tsinghua mirror for Homebrew installation"
                export HOMEBREW_CORE_GIT_URL
                export HOMEBREW_BOTTLE_DOMAIN
                git clone --depth=1 https://mirrors.tuna.tsinghua.edu.cn/git/homebrew/install.git /tmp/brew-install
                /bin/bash /tmp/brew-install/install.sh
                rm -rf /tmp/brew-install
            else
                run_remote_bash "https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh"
            fi

            # Add Homebrew to PATH for this session
            if ! activate_brew_for_session; then
                ui_warn "Homebrew install completed but brew is still unavailable in this shell"
            fi
            ui_success "Homebrew installed"
        else
            activate_brew_for_session || true
            ui_success "Homebrew already installed"
        fi
    fi
}

https://gitee.com/luckystarry/openclaw-install/raw/master/install.sh

上次更新时间:

最近更新