#!/System/Library/Frameworks/Ruby.framework/Versions/Current/usr/bin/ruby

本文解析了Homebrew的安装脚本,详细介绍了如何通过该脚本来安装Homebrew及其相关组件。文章涵盖了安装过程中的权限配置、依赖项检查与安装、Git版本控制集成等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#!/System/Library/Frameworks/Ruby.framework/Versions/Current/usr/bin/ruby
# This script installs to /usr/local only. To install elsewhere you can just
# untar https://github.com/Homebrew/brew/tarball/master anywhere you like or
# change the value of HOMEBREW_PREFIX.
HOMEBREW_PREFIX = "/usr/local".freeze
HOMEBREW_REPOSITORY = "/usr/local/Homebrew".freeze
HOMEBREW_CACHE = "#{ENV["HOME"]}/Library/Caches/Homebrew".freeze
HOMEBREW_OLD_CACHE = "/Library/Caches/Homebrew".freeze
BREW_REPO = "https://github.com/Homebrew/brew".freeze
CORE_TAP_REPO = "https://github.com/Homebrew/homebrew-core".freeze

# no analytics during installation
ENV["HOMEBREW_NO_ANALYTICS_THIS_RUN"] = "1"
ENV["HOMEBREW_NO_ANALYTICS_MESSAGE_OUTPUT"] = "1"

module Tty
  module_function

  def blue
    bold 34
  end

  def red
    bold 31
  end

  def reset
    escape 0
  end

  def bold(n = 39)
    escape "1;#{n}"
  end

  def underline
    escape "4;39"
  end

  def escape(n)
    "\033[#{n}m" if STDOUT.tty?
  end
end

class Array
  def shell_s
    cp = dup
    first = cp.shift
    cp.map { |arg| arg.gsub " ", "\\ " }.unshift(first).join(" ")
  end
end

def ohai(*args)
  puts "#{Tty.blue}==>#{Tty.bold} #{args.shell_s}#{Tty.reset}"
end

def warn(warning)
  puts "#{Tty.red}Warning#{Tty.reset}: #{warning.chomp}"
end

def system(*args)
  abort "Failed during: #{args.shell_s}" unless Kernel.system(*args)
end

def sudo(*args)
  args.unshift("-A") unless ENV["SUDO_ASKPASS"].nil?
  ohai "/usr/bin/sudo", *args
  system "/usr/bin/sudo", *args
end

def getc # NOTE only tested on OS X
  system "/bin/stty raw -echo"
  if STDIN.respond_to?(:getbyte)
    STDIN.getbyte
  else
    STDIN.getc
  end
ensure
  system "/bin/stty -raw echo"
end

def wait_for_user
  puts
  puts "Press RETURN to continue or any other key to abort"
  c = getc
  # we test for \r and \n because some stuff does \r instead
  abort unless (c == 13) || (c == 10)
end

class Version
  include Comparable
  attr_reader :parts

  def initialize(str)
    @parts = str.split(".").map(&:to_i)
  end

  def <=>(other)
    parts <=> self.class.new(other).parts
  end
end

def force_curl?
  ARGV.include?("--force-curl")
end

def macos_version
  @macos_version ||= Version.new(`/usr/bin/sw_vers -productVersion`.chomp[/10\.\d+/])
end

def should_install_command_line_tools?
  return false if force_curl?
  return false if macos_version < "10.9"
  developer_dir = `/usr/bin/xcode-select -print-path 2>/dev/null`.chomp
  developer_dir.empty? || !File.exist?("#{developer_dir}/usr/bin/git")
end

def git
  return false if force_curl?

  @git ||= if ENV["GIT"] && File.executable?(ENV["GIT"])
    ENV["GIT"]
  elsif Kernel.system "/usr/bin/which -s git"
    "git"
  else
    exe = `xcrun -find git 2>/dev/null`.chomp
    exe if $? && $?.success? && !exe.empty? && File.executable?(exe)
  end

  return unless @git
  # Github only supports HTTPS fetches on 1.7.10 or later:
  # https://help.github.com/articles/https-cloning-errors
  `#{@git} --version` =~ /git version (\d\.\d+\.\d+)/
  return if $1.nil?
  return if Version.new($1) < "1.7.10"

  @git
end

def user_only_chmod?(d)
  return false unless File.directory?(d)
  mode = File.stat(d).mode & 0777
  # u = (mode >> 6) & 07
  # g = (mode >> 3) & 07
  # o = (mode >> 0) & 07
  mode != 0755
end

def chmod?(d)
  File.exist?(d) && !(File.readable?(d) && File.writable?(d) && File.executable?(d))
end

def chown?(d)
  !File.owned?(d)
end

def chgrp?(d)
  !File.grpowned?(d)
end

# Invalidate sudo timestamp before exiting (if it wasn't active before).
Kernel.system "/usr/bin/sudo -n -v 2>/dev/null"
at_exit { Kernel.system "/usr/bin/sudo", "-k" } unless $?.success?

# The block form of Dir.chdir fails later if Dir.CWD doesn't exist which I
# guess is fair enough. Also sudo prints a warning message for no good reason
Dir.chdir "/usr"

####################################################################### script
abort "See Linuxbrew: http://linuxbrew.sh/" if RUBY_PLATFORM.to_s.downcase.include?("linux")
abort "MacOS too old, see: https://github.com/mistydemeo/tigerbrew" if macos_version < "10.6"
abort "Don't run this as root!" if Process.uid.zero?
abort <<-EOABORT unless `dsmemberutil checkmembership -U "#{ENV["USER"]}" -G admin`.include? "user is a member"
This script requires the user #{ENV["USER"]} to be an Administrator.
EOABORT
# Tests will fail if the prefix exists, but we don't have execution
# permissions. Abort in this case.
abort <<-EOABORT if File.directory?(HOMEBREW_PREFIX) && (!File.executable? HOMEBREW_PREFIX)
The Homebrew prefix, #{HOMEBREW_PREFIX}, exists but is not searchable. If this is
not intentional, please restore the default permissions and try running the
installer again:
    sudo chmod 775 #{HOMEBREW_PREFIX}
EOABORT

ohai "This script will install:"
puts "#{HOMEBREW_PREFIX}/bin/brew"
puts "#{HOMEBREW_PREFIX}/share/doc/homebrew"
puts "#{HOMEBREW_PREFIX}/share/man/man1/brew.1"
puts "#{HOMEBREW_PREFIX}/share/zsh/site-functions/_brew"
puts "#{HOMEBREW_PREFIX}/etc/bash_completion.d/brew"
puts HOMEBREW_REPOSITORY.to_s

group_chmods = %w[ bin bin/brew etc Frameworks include lib sbin share var
                   etc/bash_completion.d lib/pkgconfig var/log
                   share/aclocal share/doc share/info share/locale share/man
                   share/man/man1 share/man/man2 share/man/man3 share/man/man4
                   share/man/man5 share/man/man6 share/man/man7 share/man/man8].
               map { |d| File.join(HOMEBREW_PREFIX, d) }.
               select { |d| chmod?(d) }
# zsh refuses to read from these directories if group writable
zsh_dirs = %w[share/zsh share/zsh/site-functions].
           map { |d| File.join(HOMEBREW_PREFIX, d) }
user_chmods = zsh_dirs.select { |d| user_only_chmod?(d) }
chmods = group_chmods + user_chmods
chowns = chmods.select { |d| chown?(d) }
chgrps = chmods.select { |d| chgrp?(d) }
mkdirs = %w[Cellar Homebrew Frameworks bin etc include lib opt sbin share share/zsh share/zsh/site-functions var].
         map { |d| File.join(HOMEBREW_PREFIX, d) }.
         reject { |d| File.directory?(d) }

unless group_chmods.empty?
  ohai "The following existing directories will be made group writable:"
  puts(*group_chmods)
end
unless user_chmods.empty?
  ohai "The following existing directories will be made writable by user only:"
  puts(*user_chmods)
end
unless chowns.empty?
  ohai "The following existing directories will have their owner set to #{Tty.underline}#{ENV["USER"]}#{Tty.reset}:"
  puts(*chowns)
end
unless chgrps.empty?
  ohai "The following existing directories will have their group set to #{Tty.underline}admin#{Tty.reset}:"
  puts(*chgrps)
end
unless mkdirs.empty?
  ohai "The following new directories will be created:"
  puts(*mkdirs)
end

wait_for_user if STDIN.tty? && !ENV["TRAVIS"]

if File.directory? HOMEBREW_PREFIX
  sudo "/bin/chmod", "u+rwx", *chmods unless chmods.empty?
  sudo "/bin/chmod", "g+rwx", *group_chmods unless group_chmods.empty?
  sudo "/bin/chmod", "755", *user_chmods unless user_chmods.empty?
  sudo "/usr/sbin/chown", ENV["USER"], *chowns unless chowns.empty?
  sudo "/usr/bin/chgrp", "admin", *chgrps unless chgrps.empty?
else
  sudo "/bin/mkdir", "-p", HOMEBREW_PREFIX
  sudo "/usr/sbin/chown", "root:wheel", HOMEBREW_PREFIX
end

unless mkdirs.empty?
  sudo "/bin/mkdir", "-p", *mkdirs
  sudo "/bin/chmod", "g+rwx", *mkdirs
  sudo "/bin/chmod", "755", *zsh_dirs
  sudo "/usr/sbin/chown", ENV["USER"], *mkdirs
  sudo "/usr/bin/chgrp", "admin", *mkdirs
end

[HOMEBREW_CACHE, HOMEBREW_OLD_CACHE].each do |cache|
  sudo "/bin/mkdir", "-p", cache unless File.directory? cache
  sudo "/bin/chmod", "g+rwx", cache if chmod? cache
  sudo "/usr/sbin/chown", ENV["USER"], cache if chown? cache
  sudo "/usr/bin/chgrp", "admin", cache if chgrp? cache
end

if should_install_command_line_tools?
  ohai "Searching online for the Command Line Tools"
  # This temporary file prompts the 'softwareupdate' utility to list the Command Line Tools
  clt_placeholder = "/tmp/.com.apple.dt.CommandLineTools.installondemand.in-progress"
  sudo "/usr/bin/touch", clt_placeholder
  clt_label = `softwareupdate -l | grep -B 1 -E "Command Line (Developer|Tools)" | awk -F"*" '/^ +\\*/ {print $2}' | sed 's/^ *//' | tail -n1`.chomp
  ohai "Installing #{clt_label}"
  sudo "/usr/sbin/softwareupdate", "-i", clt_label
  sudo "/bin/rm", "-f", clt_placeholder
  sudo "/usr/bin/xcode-select", "--switch", "/Library/Developer/CommandLineTools"
end

# Headless install may have failed, so fallback to original 'xcode-select' method
if should_install_command_line_tools? && STDIN.tty?
  ohai "Installing the Command Line Tools (expect a GUI popup):"
  sudo "/usr/bin/xcode-select", "--install"
  puts "Press any key when the installation has completed."
  getc
  sudo "/usr/bin/xcode-select", "--switch", "/Library/Developer/CommandLineTools"
end

abort <<-EOABORT if `/usr/bin/xcrun clang 2>&1` =~ /license/ && !$?.success?
You have not agreed to the Xcode license.
Before running the installer again please agree to the license by opening
Xcode.app or running:
    sudo xcodebuild -license
EOABORT

ohai "Downloading and installing Homebrew..."
Dir.chdir HOMEBREW_REPOSITORY do
  if git
    # we do it in four steps to avoid merge errors when reinstalling
    system git, "init", "-q"

    # "git remote add" will fail if the remote is defined in the global config
    system git, "config", "remote.origin.url", BREW_REPO
    system git, "config", "remote.origin.fetch", "+refs/heads/*:refs/remotes/origin/*"

    # ensure we don't munge line endings on checkout
    system git, "config", "core.autocrlf", "false"

    args = git, "fetch", "origin", "master:refs/remotes/origin/master",
           "--tags", "--force"
    args << "--depth=1" unless ARGV.include?("--full") || !ENV["HOMEBREW_DEVELOPER"].nil?
    system(*args)

    system git, "reset", "--hard", "origin/master"

    system "ln", "-sf", "#{HOMEBREW_REPOSITORY}/bin/brew", "#{HOMEBREW_PREFIX}/bin/brew"

    system "#{HOMEBREW_PREFIX}/bin/brew", "update", "--force"
  else
    # -m to stop tar erroring out if it can't modify the mtime for root owned directories
    # pipefail to cause the exit status from curl to propagate if it fails
    curl_flags = "fsSL"
    core_tap = "#{HOMEBREW_PREFIX}/Homebrew/Library/Taps/homebrew/homebrew-core"
    system "/bin/bash -o pipefail -c '/usr/bin/curl -#{curl_flags} #{BREW_REPO}/tarball/master | /usr/bin/tar xz -m --strip 1'"

    system "ln", "-sf", "#{HOMEBREW_REPOSITORY}/bin/brew", "#{HOMEBREW_PREFIX}/bin/brew"

    system "/bin/mkdir", "-p", core_tap
    Dir.chdir core_tap do
      system "/bin/bash -o pipefail -c '/usr/bin/curl -#{curl_flags} #{CORE_TAP_REPO}/tarball/master | /usr/bin/tar xz -m --strip 1'"
    end
  end
end

warn "#{HOMEBREW_PREFIX}/bin is not in your PATH." unless ENV["PATH"].split(":").include? "#{HOMEBREW_PREFIX}/bin"

ohai "Installation successful!"
puts

# Use the shell's audible bell.
print "\a"

# Use an extra newline and bold to avoid this being missed.
ohai "Homebrew has enabled anonymous aggregate user behaviour analytics."
puts <<-EOS
#{Tty.bold}Read the analytics documentation (and how to opt-out) here:
  #{Tty.underline}https://docs.brew.sh/Analytics.html#{Tty.reset}

EOS

if git
  Dir.chdir HOMEBREW_REPOSITORY do
    system git, "config", "--local", "--replace-all", "homebrew.analyticsmessage", "true"
  end
end

ohai "Next steps:"

if macos_version < "10.9" && macos_version > "10.6"
  `/usr/bin/cc --version 2> /dev/null` =~ /clang-(\d{2,})/
  version = $1.to_i
  if version < 425
    puts "- Install the #{Tty.bold}Command Line Tools for Xcode:"
    puts "    #{Tty.underline}https://developer.apple.com/downloads#{Tty.reset}"
  end
elsif !File.exist? "/usr/bin/cc"
  puts "- Install #{Tty.bold}Xcode:"
  puts "    #{Tty.underline}https://developer.apple.com/xcode#{Tty.reset}"
end

unless git
  puts "- Run `brew update --force` to complete installation by installing:"
  puts "    #{HOMEBREW_PREFIX}/share/doc/homebrew"
  puts "    #{HOMEBREW_PREFIX}/share/man/man1/brew.1"
  puts "    #{HOMEBREW_PREFIX}/share/zsh/site-functions/_brew"
  puts "    #{HOMEBREW_PREFIX}/etc/bash_completion.d/brew"
  puts "    #{HOMEBREW_REPOSITORY}/.git"
end

puts "- Run `brew help` to get started"
puts "- Further documentation: "
puts "    #{Tty.underline}https://docs.brew.sh#{Tty.reset}"

转载于:https://www.cnblogs.com/20170722-kong/p/7506889.html

<think>好的,我现在需要帮助用户解决关于在macOS上设置Python别名的问题。用户提到了路径/Library/Frameworks/Python.framework/Versions/3.11/bin/python3.11,并且引用了几个相关的引用内容。我需要先理解用户的问题到底是什么。 首先,用户想知道Python别名指向路径的意义以及如何设置这个别名。他们可能在自己的Mac上安装了多个Python版本,或者通过源码安装,导致默认的python命令指向了错误的版本,比如系统自带的Python 2.7,而他们想使用自己安装的Python 3.11。这时候,设置别名可以方便他们在终端中直接输入python来调用想要的版本。 接下来,我需要结合用户提供的引用内容。引用[1]、[3]和[5]都提到了通过alias命令来设置别名,比如alias python="/Library/Frameworks/.../python3.11"。引用[5]还详细说明了不同shell下的环境变量配置方法,比如bash、csh等,这对于用户来说可能有帮助,特别是他们需要根据自己使用的shell来配置。 用户可能是在问如何永久设置这个别名,而不仅仅是临时在终端会话中使用。临时设置的话,直接在终端输入alias命令即可,但关闭终端后就失效了。所以用户可能需要知道如何将别名添加到shell的配置文件中,比如.bashrc、.zshrc等,这样每次启动终端都会自动生效。 另外,引用[4]和[5]提到了修改PATH环境变量,这可能与别名设置有关联,但用户的问题主要是关于别名而不是PATH。不过,有时候用户可能混淆这两个概念,需要解释清楚别名和环境变量的区别。别名是给命令起一个简短的名称,而PATH是系统查找可执行文件的路径。 用户可能还遇到了权限问题,比如在修改配置文件时没有权限保存,或者配置文件的位置不正确。比如,在macOS Catalina及以后版本,默认的shell是zsh,所以需要编辑的是~/.zshrc而不是~/.bashrc。如果用户没有意识到这一点,可能会导致配置不生效。 需要逐步引导用户如何检查当前使用的shell,找到对应的配置文件,添加alias命令,然后应用更改。同时,提醒用户如果路径有误,或者Python解释器的位置不正确,别名可能无法正常工作,所以需要先验证路径是否正确。 可能还需要解释为什么设置别名是有用的:比如避免每次输入完整路径,简化命令行操作,确保使用正确的Python版本进行开发,尤其是当系统中有多个Python安装时。 最后,生成相关问题需要考虑用户可能的后续疑问,比如如何切换不同版本的Python,使用虚拟环境,或者处理别名冲突等问题。</think>在macOS中设置Python别名指向指定路径,可以通过`alias`命令将`python`指向特定版本的解释器,从而简化终端操作。以下是具体步骤及意义说明: --- ### **一、设置Python别名的意义** 1. **统一调用方式** 当系统中安装多个Python版本时(如系统自带的Python 2.7和自行安装的Python 3.11),别名可快速指定默认调用的版本[^5]。 2. **简化命令输入** 直接输入`python`替代完整路径`/Library/Frameworks/.../python3.11`,提升效率。 3. **兼容脚本依赖** 确保脚本中`#!/usr/bin/env python`自动指向目标版本。 --- ### **二、临时设置别名(仅当前终端生效)** 在终端直接运行: ```bash alias python="/Library/Frameworks/Python.framework/Versions/3.11/bin/python3.11" ``` 验证是否生效: ```bash python --version # 应显示Python 3.11.x ``` --- ### **三、永久设置别名** 需将别名写入Shell配置文件,具体步骤因Shell类型而异: 1. **确认当前Shell类型** 执行`echo $SHELL`: - `/bin/zsh` → 编辑`~/.zshrc` - `/bin/bash` → 编辑`~/.bash_profile`或`~/.bashrc` 2. **编辑配置文件** 以zsh为例: ```bash nano ~/.zshrc ``` 在文件末尾添加: ```bash alias python="/Library/Frameworks/Python.framework/Versions/3.11/bin/python3.11" ``` 3. **应用配置** ```bash source ~/.zshrc # 使配置立即生效 ``` --- ### **四、验证别名是否生效** ```bash which python # 应输出别名路径 python --version # 检查版本 ``` --- ### **五、注意事项** 1. **路径正确性** 确保路径`/Library/Frameworks/.../python3.11`实际存在,否则别名会失效[^2]。 2. **优先级冲突** 若`PATH`环境变量已包含其他Python路径,需调整路径顺序或直接使用别名覆盖[^4]。 3. **跨终端兼容性** 永久配置需根据Shell类型修改对应文件,否则新终端可能不生效。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值