Get return code and output from command in Perl

10,474

Solution 1

After backticks are run, the return code is available in $?.

$?

The status returned by the last pipe close, backtick (``) command, successful call to wait() or waitpid(), or from the system() operator. This is just the 16-bit status word returned by the traditional Unix wait() system call (or else is made up to look like it).

$output = `$some_command`;
print "Output of $some_command was '$output'.\n";
print "Exit code of $some_command was $?\n";

Solution 2

The universal solution for backticks, system(), etc is to use the ${^CHILD_ERROR_NATIVE} variable. See the perlvar perldoc: http://perldoc.perl.org/perlvar.html#%24%7b%5eCHILD_ERROR_NATIVE%7d

${^CHILD_ERROR_NATIVE} The native status returned by the last pipe close, backtick (`` ) command, successful call to wait() or waitpid(), or from the system() operator. On POSIX-like systems this value can be decoded with the WIFEXITED, WEXITSTATUS, WIFSIGNALED, WTERMSIG, WIFSTOPPED, WSTOPSIG and WIFCONTINUED functions provided by the POSIX module.

Share:
10,474
coconut
Author by

coconut

Updated on July 24, 2022

Comments

  • coconut
    coconut almost 2 years

    I'm trying to write a utility that will go through a file that would look like this:

    # Directory | file name | action | # of days without modification to the file for the command to take action
    /work/test/|a*|delete|1
    /work/test/|b*|compress|0
    /work/test/|c*|compress|1
    

    My script will go through the file deciding if, for example, there are files under /work/test/ that start with 'a' that haven't been modified in the last 1 days, and if so, it would delete them.

    For this, I use the find command. Example:

    my $command = "find " . $values[0] . $values[1] . " -mtime +" . $values[3] . " -delete ;\n";
    system ($command);
    

    But, I've been asked to retrieve the return code for each step to verify that the every step worked fine.

    Now, I know that system() returns the return code, and the backticks return the output. But, how can I get both?

  • ikegami
    ikegami over 8 years
    Tip: All of system, readpipe (backticks), wait and waitpid set $?.
  • Sobrique
    Sobrique over 8 years
    Also note - it won't necessarily be the return code of the command - you may need to bit shift it.
  • ikegami
    ikegami over 8 years
    The documentation for system shows how to extra the different values from $?.
  • mob
    mob over 8 years