【问题标题】:How to Bash Script Git Local Branch Check?如何 Bash 脚本 Git 本地分支检查?
【发布时间】:2013-01-02 23:49:25
【问题描述】:

寻求实现以下目标的解决方案:

  • 如果当前未在本地创建上创建分支
  • 如果已存在提示用户并移至下一条语句

到目前为止,我已经让它工作了,但还没有完全到位。我的问题确实是后者,但我想花点时间重新思考整个事情,并就如何更合理地写出一些反馈。

变量 existing_branch 提供 SHArefs/heads/branchName 当分支存在时,git 会占据并提供预期的 fatal:

check_for_branch() {
 args=("$@")
 echo `$branch${args[0]}`
 existing_branch=$?
}

create_branch() {
  current="git rev-parse --abbrev-ref HEAD"
  branch="git show-ref --verify refs/heads/"

  args=("$@")
  branch_present=$(check_for_branch ${args[0]})
  echo $branch_present
  read -p "Do you really want to create branch $1 " ans
  case $ans in
    y | Y | yes | YES | Yes)
        if [  ! -z branch_present ]; then
          echo  "Branch already exists"
        else
          `git branch ${args[0]}`
          echo  "Created ${args[0]} branch"
        fi
    ;;
     n | N | no | NO | No)
      echo "exiting"
    ;;
    *)
    echo "Enter something I can work with y or n."
    ;;
    esac
}

【问题讨论】:

    标签: git bash scripting


    【解决方案1】:

    如果分支已经存在,可以避免提示,稍微缩短脚本,像这样:

    create_branch() {
      branch="${1:?Provide a branch name}"
    
      if git show-ref --verify --quiet "refs/heads/$branch"; then
        echo >&2 "Branch '$branch' already exists."
      else
        read -p "Do you really want to create branch $1 " ans
        ...
      fi
    }
    

    【讨论】:

    • 感谢您按我的预期工作。 bash 脚本的新手,想多解释一下如何在第 2 行和第 5 行中使用花括号和技术?
    • 查看POSIXbashredirection中的参数扩展。 >&2 表示echo 进入stderr,而不是stdout。
    猜你喜欢
    • 2016-06-29
    • 2017-10-09
    • 2015-07-22
    • 1970-01-01
    • 2011-04-20
    • 2017-02-09
    • 2012-03-05
    • 2018-09-12
    • 1970-01-01
    相关资源
    最近更新 更多