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

use*_*030 4 linux bash shell gnome-terminal

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

    my_func() {
        // Do cool stuff
    }

    gnome-terminal -x my_func
Run Code Online (Sandbox Code Playgroud)

我现在正在做的是将 my_func() 放入脚本并调用 gnome-terminal -x ./my_func

mkl*_*nt0 5

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'
Run Code Online (Sandbox Code Playgroud)

我从/sf/answers/1312960911/借用了该技术


通过一些技巧,您可以不用export -f,假设在运行该函数后保持打开状态的 bash 实例本身不需要继承my_func.

declare -f返回的定义(源代码),my_func因此只需在新的 bash 实例中重新定义它:

gnome-terminal -x bash -c "$(declare -f my_func); my_func; bash"
Run Code Online (Sandbox Code Playgroud)

再说一次,如果您愿意,您甚至可以将export -f命令挤在那里:

gnome-terminal -x bash -c "$(declare -f my_func); 
  export -f my_func; my_func; bash"
Run Code Online (Sandbox Code Playgroud)