【问题标题】:Running a bash function in gnome-terminal -x在 gnome-terminal -x 中运行 bash 函数
【发布时间】:2014-04-11 01:50:14
【问题描述】:

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

    my_func() {
        // Do cool stuff
    }

    gnome-terminal -x my_func

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

【问题讨论】:

  • 你试过用export -f导出函数吗?
  • 我刚刚尝试了export -f my_func,然后运行gnome-terminal -x my_func 没有结果。真可惜。

标签: linux bash shell gnome-terminal


【解决方案1】:

您可以让它与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"

【讨论】:

  • Bravo mklement0!在进程终止后我不需要窗口保持打开状态,所以我跳过了my_func; bash 中的 bash 部分。谢谢你的好东西!
  • @user985030:我很高兴。我很高兴它对你有用。
猜你喜欢
  • 1970-01-01
  • 2019-10-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-19
  • 2015-11-23
相关资源
最近更新 更多