您可以將其與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"