【问题标题】:Is there any better way to execute several system commands from a rake task?有没有更好的方法从 rake 任务中执行多个系统命令?
【发布时间】:2016-06-08 09:45:42
【问题描述】:

我的葫芦项目中有一个 rake 任务,它执行几个系统命令,例如:

desc 'Export and execute features from JIRA '
  task :run_jira, [:key, :language, :apk_file] do |_, args|
  key = args[:key]
  language = args[:language] || 'en'
  apk_file = args[:apk_file] || default_apk
  system "curl -u admin:admin -X GET http://myjira/rest/raven/1.0/export/test?keys=#{key} > jira.zip"
  system "unzip -o jira.zip -d features/jira"
  system "rm -rf jira.zip"
  system "calabash-android run #{apk_file} -p android -p #{language} -p common -f json -o results/reports/calabash-#{key}.json  features/jira"
  system "curl -H 'Content-Type: application/json' -X POST -u admin:admin --data @results/reports/calabash-#{key}.json http://myjira/rest/raven/1.0/import/execution/cucumber"
end

有没有更好的方法来执行这 5 个系统调用?我的想法是制作一个 .sh 脚本并从任务中启动它,但由于该脚本将在 OS X 和 Linux 机器上执行,我认为它可能会造成更多麻烦。

【问题讨论】:

    标签: ruby rake


    【解决方案1】:

    您可以将所有这些命令合并为一个命令并执行该命令。假设您创建了一个包含所有命令的数组 commands,您可以这样做:

    composite_command = commands.join('; ')
    system(composite_command)
    

    如果您希望在任何包含错误的情况下停止执行,您可以将分号替换为双 & 和号:

    composite_command = commands.join(' && ')
    system(composite_command)
    

    这说明了&& 的作用:

    $ ls foo && echo hi
    ls: foo: No such file or directory
    $ touch foo
    $ ls foo && echo hi
    foo
    hi
    

    shell 将失败定义为返回 0 以外的退出代码。

    最大命令长度,但我希望它始终至少为 1024。

    【讨论】:

    • P.S.如果遇到奇怪的问题,您可能需要将命令的某些部分放在双引号中——使用%q{} 构建字符串会使这更容易;和/或您可能会发现您需要使用 Shellwords.shellescape 来执行命令。
    猜你喜欢
    • 2010-11-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-10
    相关资源
    最近更新 更多