Search code examples
shellpowershellcmdrubygemsappveyor

If-else and error handing in command prompt


I am trying to detect if certain ruby gem is not installed, install it first and then proceed.

For instance:

gem which rails

returns path to gem's driver file (.rb) on stdout, if gem exists, if not it checks throws error on stderr.

How can I solve it?

Pseudo code:

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

Either cmd or powershell would work.

I need to add these in AppVeyor CI yaml configuration file. AppVeyor CI has this wonderful feature of caching the directory for DRY'ing installations to improve build performance. So I have cached the gems directory and it restores fine on running the build, but then gem install reinstalls the gem anyway!


Solution

  • By using powershell to run the command you can use error redirection to check if the command was successful:

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

    Explanation: We're telling powershell to store the result of "gem which example3" in the variable $gemPath, however if there is an error we want to redirect the error to the variable $null by using 2>$null

    You can also replace 2 with the number corresponding to the stream you'd like to capture (Success, Error, Warning etc)

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

    More on redirection here About_Redirection