使用 Bash 将字符串转换为 Git 分支名称格式

Transform string into Git branch name format with Bash

懒惰的程序员,我正在制作一个简单的 shell 脚本,它从用户输入中获取一个分支名称,将该名称转换为正确的格式并在本地创建新分支,然后将其推送到远程。

所以我们的目标是转换一个字符串,例如'Mary had a little lamb' 转换为 'mary-had-a-little-lamb',沿途删除所有不是数字或字母的字符,并将所有空格(单个或多个)替换为 -.

我有一个可行的解决方案,但它看起来很丑陋,我该如何改进它?

另外,有没有办法检查指定的分支是否已经在本地存在,只有在不存在的情况下才继续?

#!/bin/bash
currentBranch=$(git branch --show-current)
echo "Checking out from branch $currentBranch"
echo "Enter new branch name:"
read branchName
branchName=$(echo $branchName | tr -d ':-') #remove special characters
branchName=$(echo $branchName | tr -s ' ') #replace multiple spaces with one
branchName=$(echo $branchName | tr ' ' '-') #replace spaces with -
branchName=${branchName,,}

echo "Checking out new branch $branchName..."
git checkout -b $branchName
echo "Pushing new branch $branchName to the remote..."
git push origin $branchName

我建议您使用 sed 来通过 sed 清理您的分支名称,如下所示:

sanitized_branch_name=$(echo ${branchName} | sed -E 's/\s+/\s/g' | sed -E 's/[\s:]/\-/g')

关于如何检查分支是否足够:


if git branch -a | grep $sanitized_branch_name 2>& 1>/dev/null; then
  echo "${sanitized_branch_name} branch exists!"
fi

编辑(示例输出):

$ branchName="antonio  petri:cca"

$ echo ${branchName} | sed -E 's/\s+/\s/g' | sed -E 's/[\s:]/\-/g'

antonio-petri-cca

您可以使用 Bash 的内置字符串替换:

#!/usr/bin/env bash

# Take this for a test
branch_name='foo bar    baz:: ::: qux----corge'

# Need extglob for the pattern to replace
shopt -s extglob

# Do the substition with extglob pattern
#san_branch_name="${branch_name//+([[:punct:][:space:]-])/-}"
# this is a shorter filter for valid git identifiers
san_branch_name="${branch_name//+([^[:alnum:]])/-}"


# For debug purposes
declare -p branch_name san_branch_name

实际输出:

declare -- branch_name="foo bar    baz:: ::: qux----corge"
declare -- san_branch_name="foo-bar-baz-qux-corge"