在gnome-terminal -x中运行一个bash函数

我有一个bash函数,我想使用gnometerminal在新窗口中执行该函数。 我该怎么做? 我想在blah.sh脚本中做这样的事情:

my_func() { // Do cool stuff } gnome-terminal -x my_func 

我现在正在做的是把my_func()放到一个脚本中,然后调用gnome-terminal -x ./my_func

你可以使用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' 

我借用了https://stackoverflow.com/a/18756584/45375的技巧


有一些诡计,你可以做,而不会export -f ,假设运行该函数后保持打开的bash实例本身不需要继承my_func

declare -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"