How can I delete all Git branches which have been merged?

后端 未结 30 1087
离开以前
离开以前 2020-11-22 14:22

I have many Git branches. How do I delete branches which have already been merged? Is there an easy way to delete them all instead of deleting them one by one?

30条回答
  •  忘了有多久
    2020-11-22 15:06

    I use the following Ruby script to delete my already merged local and remote branches. If I'm doing it for a repository with multiple remotes and only want to delete from one, I just add a select statement to the remotes list to only get the remotes I want.

    #!/usr/bin/env ruby
    
    current_branch = `git symbolic-ref --short HEAD`.chomp
    if current_branch != "master"
      if $?.exitstatus == 0
        puts "WARNING: You are on branch #{current_branch}, NOT master."
      else
        puts "WARNING: You are not on a branch"
      end
      puts
    end
    
    puts "Fetching merged branches..."
    remote_branches= `git branch -r --merged`.
      split("\n").
      map(&:strip).
      reject {|b| b =~ /\/(#{current_branch}|master)/}
    
    local_branches= `git branch --merged`.
      gsub(/^\* /, '').
      split("\n").
      map(&:strip).
      reject {|b| b =~ /(#{current_branch}|master)/}
    
    if remote_branches.empty? && local_branches.empty?
      puts "No existing branches have been merged into #{current_branch}."
    else
      puts "This will remove the following branches:"
      puts remote_branches.join("\n")
      puts local_branches.join("\n")
      puts "Proceed?"
      if gets =~ /^y/i
        remote_branches.each do |b|
          remote, branch = b.split(/\//)
          `git push #{remote} :#{branch}`
        end
    
        # Remove local branches
        `git branch -d #{local_branches.join(' ')}`
      else
        puts "No branches removed."
      end
    end
    

提交回复
热议问题