Хорошо, я нашел, как автоматически экспортировать переменные, чтобы запустить интерактивную оболочку для тестирования:set -a
в верхней части скрипта.
#!/bin/bash
if [ "${0}" != "${BASH_SOURCE[0]}" ] ; then
echo "This script should not be sourced" >&2
return 1
fi
set -a # automatically export all vars
SOME_VAR="hey"
checker() {
# can find fatal conditions which should exit the script
# or stop sourcing it
#... do some checks
# if all OK
return 0
# otherwise stop
exit 1
}
# some more function definitions...
# do some checks to see if the current environment is supported
checker "some_fatal_condition" # need to stop sourcing here
checker "some_other_condition"
# if the script is being sourced for testing purposes, stop now
if [ "${1}" == "test" ] ; then
PS1="test> " bash
exit $?
fi
echo "proceeding"
# actual stuff follows, only if executing
#...
Вы не должны exit
внутри функции, если только она явно не является обработчиком ошибок/выходов. Предпочтительнее return
из функции.
Другой способ отделить функции от тела скрипта состоит в том, чтобы :поместить ваши функции в отдельный файл и включить их в скрипт.