【问题标题】:how to call shell commands from groovy correctly如何正确地从 groovy 调用 shell 命令
【发布时间】:2012-09-12 20:04:55
【问题描述】:

我想从我的 groovy 脚本中执行 shell 命令。 我测试了以下内容:

"mkdir testdir".execute()

这很好用。 现在我想创建一个文件,向文件中写入一些内容,然后打开文本编辑器来查看文件。

def execute(cmd) {
   def proc =  cmd.execute()
   proc.waitFor()
}

execute("touch file")
execute("echo hello > file")
execute("gedit file")

现在 gedit 可以正确打开,但文件中没有“hello”字符串。 这是怎么回事?!?

【问题讨论】:

    标签: file shell groovy command


    【解决方案1】:

    您不能在该行中进行重定向:

    execute("echo hello > file")
    

    所以没有任何东西被写入文件。处理此问题的最简单方法可能是将所有命令包装到一个 shell 脚本中,然后执行此脚本。

    否则,您可以从echo 命令读取标准输出(不带> file),然后在 Groovy 中自己将其写入file

    或者你可以这样做:

    execute( [ 'bash', '-c', 'echo hello > file' ] )
    

    这应该作为你的execute 方法将只执行the List.execute() method

    【讨论】:

    • 我对@9​​87654329@一无所知;也就是说,有没有办法告诉execute 方法在执行前将命令行传递给shell 进行处理,比如Python subprocess 模块的shell=True 选项?
    • @chepner 实际上,你是对的......有一种方法......添加到答案中
    猜你喜欢
    • 2016-07-24
    • 2010-09-05
    • 1970-01-01
    • 2010-09-14
    • 2010-09-27
    • 2011-08-22
    • 1970-01-01
    • 2010-11-27
    相关资源
    最近更新 更多