【问题标题】:How to execute a function from a shell-script from C如何从 C 的 shell 脚本执行函数
【发布时间】:2014-04-14 19:41:59
【问题描述】:

我有一个用户提供的脚本,例如

#!/bin/sh

some_function () {
    touch some_file
}

some_other_function () {
    touch some_other_file
}

我想从 c 代码调用函数 some_other_function。

我明白,我可以简单地编写一个类似的 shell 脚本

#!/bin/sh

source userscript.sh
some_other_function

并使用 system() 执行它,但我正在寻找一种更优雅,尤其是更通用的解决方案,它可以让我执行任意命名的函数,甚至可以让我获取/设置变量。

【问题讨论】:

  • c 不能动态加载解释代码
  • c 可以exec 一个外部程序/shell,所以exec('sh yourscript.sh foo bar baz');,基本上,foo bar baz 成为外部脚本的参数。
  • 你可以通过source bash然后调用函数来执行函数。例如bash -c ". myfuncs.sh ; call_to_func arg1"
  • /bin/sh 不是 bash(好吧,从技术上讲,它可能由 bash 提供,但不是一回事)。
  • @Steve Cox:我知道这一点。正如问题中所述,我已经以某种方式解决了这个问题。但我不想为我从 shellscript 调用的每个函数提供单独的 shellscript。我只是在寻找一种更优雅/更通用的方式来做到这一点。

标签: c bash shell


【解决方案1】:

您不能直接从 C 中执行此操作。但是,您可以使用 system 从 C 中运行命令(如 sh):

// Run the command: sh -c 'source userscript.sh; some_other_function'
system("sh -c 'source userscript.sh; some_other_function'");

(请注意,sh -c '<em>command</em>' 允许您在 shell 中运行 <em>command</em>。)

或者,您也可以使用execlpexec 系列中的一些其他功能:

// Run the command: sh -c 'source userscript.sh; some_other_function'
execlp("sh", "sh", "-c", "source userscript.sh; some_other_function", NULL);

(这里注意,使用exec函数时,第一个参数-"sh"-必须重复

【讨论】:

    【解决方案2】:

    根据 cmets,我了解到您想要调用脚本中定义的几个函数之一。你可以这样做,如果你将函数作为参数提供给 shell 脚本并且在最后一行只有$1,例如

    fun1()
    {
        echo "fun1 called"
    }
    
    fun2()
    {
        echo "fun2 called"
    }
    
    $1
    

    然后您可以将您的脚本称为

    sh userscript.sh fun1
    

    给了

    fun1 调用

    【讨论】:

    • 很确定这不起作用,但可能是错误的,但只是尝试使用 bash 并且您不能在这样的 bash 脚本中调用/调用函数,至少我不能在我的当前框。
    • @ipatch 确实有效,我自己试过了。请参阅添加的示例。
    猜你喜欢
    • 1970-01-01
    • 2011-04-13
    • 1970-01-01
    • 2013-12-17
    • 2016-10-19
    • 1970-01-01
    • 2016-08-14
    • 1970-01-01
    • 2013-06-13
    相关资源
    最近更新 更多