【问题标题】:If-else and error handing in command prompt命令提示符中的 if-else 和错误处理
【发布时间】:2015-03-04 01:29:15
【问题描述】:

我正在尝试检测是否未安装某些 ruby​​ gem,请先安装它然后继续。

例如:

gem which rails

返回stdout 上 gem 的驱动程序文件 (.rb) 的路径,如果 gem 存在,则检查 stderr 上的抛出错误。

我该如何解决?

伪代码:

if throws "gem which example1" ( gem install example1 )
if throws "gem which example2" ( gem install example2 )
if throws "gem which example3" ( gem install example3 )

:: install other stuff

cmd 或 powershell 都可以。

我需要在 AppVeyor CI yaml 配置文件中添加这些。 AppVeyor CI 具有缓存 DRY 安装目录以提高构建性能的出色功能。所以我已经缓存了 gems 目录,它在运行构建时恢复得很好,但是gem install 无论如何都会重新安装 gem!

【问题讨论】:

    标签: shell powershell cmd gem appveyor


    【解决方案1】:

    使用powershell运行命令可以使用错误重定向来检查命令是否成功:

    $gemPath = gem which example3 2>$null
    
    if ($gemPath)
    {
        # We got a path for the gem driver
    }
    else
    {
        # Failed, gem might not be installed
    }
    

    解释:我们告诉 powershell 将 "gem which example3" 的结果存储在变量 $gemPath 中,但是如果出现错误,我们希望使用 2>$null 将错误重定向到变量 $null

    您还可以将 2 替换为与您要捕获的流对应的数字(成功、错误、警告等)

        *   All output
        1   Success output
        2   Errors
        3   Warning messages
        4   Verbose output
        5   Debug messages
    

    更多关于重定向在这里About_Redirection

    【讨论】:

    • 非常感谢!我只会使用if(!gemPath) { gem install blah }。 :)
    【解决方案2】:

    试试,在 .cmd 脚本中:

    gem which rails 1>nul 2>&1
    IF ERRORLEVEL 1 (gem install rails)
    

    我在这里假设您希望输出到 stdout 和 stderr 用于此批处理脚本的目的 - 否则,删除 1>nul 2>&1。

    【讨论】:

    • 谢谢。实际上删除 1>nul 2>&1 将导致 AppVeyor CI 抛出错误并将构建作业标记为失败。我主要是在寻找这个解决方案。 PowerShell 和 CMD 解决方案在 AppVeyor 上同样有用! :)
    猜你喜欢
    • 1970-01-01
    • 2017-08-09
    • 2016-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-02
    相关资源
    最近更新 更多