Leaving sourced shell script without exiting terminal

江枫思渺然 提交于 2021-01-27 14:30:39

问题


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 exiting 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 sourced 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!