问题
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
$ ...
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).
Is there an alternative to exit
ing the functions, which also exits the terminal?
回答1:
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...
}
That way the functions are short-circuited, but no shell-level exit occurs.
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.
来源:https://stackoverflow.com/questions/27552673/leaving-sourced-shell-script-without-exiting-terminal