系统相关
首页 > 系统相关> > Linux-在gnome-terminal -x中运行bash函数

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

作者:互联网

我有一个bash函数,我想使用gnome终端在新窗口中执行该函数.我该怎么做?我想在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.

声明-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"

标签:gnome-terminal,bash,shell,linux
来源: https://codeday.me/bug/20191029/1961737.html