Exit shell script without exiting terminal
I am writing a shell script to save some keystrokes and avoid typos. I would like to keep the script as a single file that calls internal methods / functions and terminates functions if problems occur 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 this via:
$ branch $ feature $ bug $ ...
I know I can source git_extensions.sh
source git_extensions.sh
in mine .bash_profile
, but when I execute one of the commands and there is no directory .git
, it will be exit 1
as expected, but that also comes out of the terminal itself (as it was received).
Is there an alternative to a exit
function that also exits the terminal?
source to share
Instead of defining a function, exit_if_no_git
define it 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...
}
Thus, the functions are short-circuited, but there is no exit at the shell level.
It is also possible to exit file source
d using return
, preventing even certain functions inside it, if return
executed at the top level inside such a file.
source to share