Search code examples
perlunit-testingstderr

How to suppress or redirect to the variable output of the system command


I am trying to execute system command for example

 system('git clone .....' );
    if ($?) {
        croak('Error while cloning git repository');
    }

Here I am checking if result is success, but how not to output the error from the system command, for example in my case, I can get somthing like

Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

From executed command.
I need to get this error into the variable and suppress it(don't print this to the terminal)
And than check this error message.
Or at least just supress it.
I need to test such subroutine in the following way

dies_ok { MyModule::sub_uses_system_command() } 'Died :(';

Is it possible to get such result ?
Thx in advance.


Solution

  • system only returns the exit status of the program that was executed, if you want to get the standard output you can use qx/command/ or backticks to execute the command:

    my $result = `git clone [...] 2>&1`
    

    You should note that the qx/command/ and backticks form of executing commands only returns STDOUT, so if you want to capture STDERR you need to redirect STDERR to STDOUT in your command.