离开源shell脚本而不退出终端 [英] Leaving sourced shell script without exiting terminal
问题描述
我正在编写一个 shell 脚本来保存一些按键并避免输入错误.我想将脚本保留为调用内部方法/函数并在出现问题时终止函数的单个文件 不离开终端.
I'm writing a shell script to save some key strokes and avoid typos. I would like to keep the script as a single file that calls internal methods/functions and terminates the functions if problems arise without leaving the terminal.
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...
}
我想通过以下方式调用它:
I would like to call it via:
$ branch
$ feature
$ bug
$ ...
我知道我可以在我的 .bash_profile
中 source git_extensions.sh
,但是当我执行其中一个命令并且没有 .git
时> 目录,它将按预期 exit 1
但这也会退出终端本身(因为它是来源).
I know I can source git_extensions.sh
in my .bash_profile
, but when I execute one of the commands and there is no .git
directory, it will exit 1
as expected but this also exits out of the terminal itself (since it's sourced).
是否有替代exit
函数的替代方法,它也会退出终端?
Is there an alternative to exit
ing the functions, which also exits the terminal?
推荐答案
与其定义一个函数exit_if_no_git
,不如定义一个has_git_dir
:
Instead of defining a function exit_if_no_git
, define one as 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
}
...还有,其他地方:
...and, elsewhere:
branch() {
has_git_dir || return
# ...actual logic here...
}
这样函数就短路了,但不会发生shell级退出.
That way the functions are short-circuited, but no shell-level exit occurs.
也可以使用 return
退出正在 source
d 的文件,如果 return
是在此类文件中的顶层运行.
It's also possible to exit a file being source
d using return
, preventing later functions within it from even being defined, if return
is run at top-level within such a file.
这篇关于离开源shell脚本而不退出终端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!