2014-12-18 35 views
3

我正在編寫一個shell腳本來保存一些關鍵筆劃並避免輸入錯誤。我想保留腳本作爲調用內部方法/函數的單個文件,並在出現問題時終止函數而不是離開終端。離開源碼的shell腳本而不退出終端

my_script.sh

#!/bin/bash 
exit_if_no_git() { 
    # if no git directory found, exit 
    # ... 
    exit 1 
} 

branch() { 
    exit_if_no_git 
    # some code... 
} 

push() { 
    exit_if_no_git 
    # some code... 
} 

feature() { 
    exit_if_no_git 
    # some code... 
} 

bug() { 
    exit_if_no_git 
    # some code... 
} 

我想通過叫它:

$ branch 
$ feature 
$ bug 
$ ... 

我知道我可以source git_extensions.sh.bash_profile,但是當我執行命令之一,有不是.git目錄,它會如預期的那樣exit 1,但是這也會退出終端本身(因爲它是來源的)。

是否有替代exit函數,這也會退出終端?

+1

您確定要使用'exit'嗎?如果你寫了你的函數開始,像'has_git_dir ||返回',這將避免該問題。同樣,你可以使用'return'來提前離開源代碼。 –

+0

@CharlesDuffy,我想這正是我要找的!我不想使用EXIT本身,但我知道唯一的其他「退出」命令是BREAK,並且不應該用於退出非循環項目。在我的快速測試中,按照您的建議使用RETURN允許我控制腳本中的工作流程。如果您想將評論更改爲答案,我會接受它。 –

+0

我更新了具有潛在技術問題的問題並接受了您的答案。謝謝! –

回答

2

而是定義一個函數exit_if_no_git的,定義一個爲has_git_dir

has_git_dir() { 
    local dir=${1:-$PWD}    # allow optional argument 
    while [[ $dir = */* ]]; do  # while not at root... 
    [[ -d $dir/.git ]] && return 0 # ...if a .git exists, return success 
    dir=${dir%/*}     # ...otherwise trim the last element 
    done 
    return 1       # if nothing was found, return failure 
} 

...以及在其他:

branch() { 
    has_git_dir || return 
    # ...actual logic here... 
} 

這樣的功能短路,但沒有殼 - 發生級別退出。


它也有可能退出文件是source d使用return,防止在其內之後從功能甚至被定義,如果return在頂層這樣的文件內運行。