2013-01-19 66 views
3

尋求一個解決方案,實現了以下內容:如何Bash腳本Git本地分支檢查?

  • 如果一個分支是不是當前在本地創建創建
  • 如果它已經存在,提示用戶,並移動到下一個語句

到目前爲止我已經得到它的工作,但不是那裏。我的問題確實是後者,但我想花點時間重新考慮整個問題,並就如何更好地編寫這些問題獲得一些反饋意見。

變量existing_branch提供SHA裁判/頭/ BRANCHNAME當一個分支是存在的,否則混帳紮根,並提供預期fatal:

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

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

    args=("[email protected]") 
    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 
} 

回答

6

你能避免提示如果分支已經存在,並縮短腳本一下,像這樣:

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 
} 
+0

謝謝你這個工作,我打算。 bash腳本新手,請注意解釋如何在第2行和第5行中使用花括號和技巧多一點? – rhodee

+0

檢查參數擴展,在[POSIX](http://pubs.opengroup.org/onlinepubs/009695399/utilities/xcu_chap02.html#tag_02_06_02)或[bash](http://www.gnu.org/software/ bash/manual/bashref.html#Shell-Parameter-Expansion)和[redirection](http://www.gnu.org/software/bash/manual/bashref.html#Redirections)。 '&&2'意味着'echo'進入stderr,而不是stdout。 – Joe