我正在编写一个 shell 脚本来保存一些击键并避免拼写错误。我想将脚本保留为单个文件,该文件调用内部方法/函数并在出现问题时终止函数without离开航站楼。
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
in my .bash_profile
,但是当我执行其中一个命令时,没有.git
目录,它将exit 1
正如预期的那样,但这也会从终端本身退出(因为它是来源的)。
有没有替代方案exit
ing 的功能,这也会退出终端?
而不是定义一个函数exit_if_no_git
,将 1 定义为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...
}
这样函数就会短路,但不会发生 shell 级退出。
也可以退出正在运行的文件source
d using return
,防止其中的后续函数被定义,如果return
在此类文件的顶层运行。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)