您可以将其与export -f一起使用,就像@kojiro的上面的注释中指出的那样.
# Define function.
my_func() {
// Do cool stuff
}
# Export it, so that all child `bash` processes see it.
export -f my_func
# Invoke gnome-terminal with `bash -c` and the function name, *plus*
# another bash instance to keep the window open.
# NOTE: This is required, because `-c` invariably exits after
# running the specified command.
# CAVEAT: The bash instance that stays open will be a *child* process of the
# one that executed the function - and will thus not have access to any
# non-exported definitions from it.
gnome-terminal -x bash -c 'my_func; bash'
借助一些技巧,您可以不用export -f,而可以假设运行该函数后保持打开状态的bash实例本身不需要继承my_func.
声明-f返回my_func的定义(源代码),因此只需在新的bash实例中重新定义它即可:
gnome-terminal -x bash -c "$(declare -f my_func); my_func; bash"
再一次,如果需要,您甚至可以在其中挤压export -f命令:
gnome-terminal -x bash -c "$(declare -f my_func);
export -f my_func; my_func; bash"