IPC::Cmd(3perl)

IPC::Cmd πŸ’– (that's the perl man page, bestie)

okay so you've stumbled into IPC::Cmd(3perl) from the Perl Programmers Reference Guide and honestly? you're so valid for that. this is the "finding and running system commands made easy" module and it fr fr does what it says on the tin. buckle up πŸŽ€


✨ NAME ✨

IPC::Cmd β€” finding and running system commands made easy πŸ’…

like. that's it. that's the whole vibe. it finds binaries and it runs them for you.


🌸 SYNOPSIS 🌸

okay bestie here's the whole look, in code, verbatim, no edits:

use IPC::Cmd qw[can_run run run_forked];

my $full_path = can_run('wget') or warn 'wget is not installed!';

### commands can be arrayrefs or strings ###
my $cmd = "$full_path -b theregister.co.uk";
my $cmd = [$full_path, '-b', 'theregister.co.uk'];

### in scalar context ###
my $buffer;
if( scalar run( command => $cmd,
                verbose => 0,
                buffer  => \$buffer,
                timeout => 20 )
) {
    print "fetched webpage successfully: $buffer\n";
}

### in list context ###
my( $success, $error_message, $full_buf, $stdout_buf, $stderr_buf ) =
        run( command => $cmd, verbose => 0 );

if( $success ) {
    print "this is what the command printed:\n";
    print join "", @$full_buf;
}

### run_forked example ###
my $result = run_forked("$full_path -q -O - theregister.co.uk", {'timeout' => 20});
if ($result->{'exit_code'} eq 0 && !$result->{'timeout'}) {
    print "this is what wget returned:\n";
    print $result->{'stdout'};
}

### check for features
print "IPC::Open3 available: "  . IPC::Cmd->can_use_ipc_open3;
print "IPC::Run available: "    . IPC::Cmd->can_use_ipc_run;
print "Can capture buffer: "    . IPC::Cmd->can_capture_buffer;

### don't have IPC::Cmd be verbose, ie don't print to stdout or
### stderr when running commands -- default is '0'
$IPC::Cmd::VERBOSE = 0;

it's giving "I have options and I'm not afraid to use them." ✨


πŸ¦‹ DESCRIPTION πŸ¦‹

so IPC::Cmd lets you run commands platform independently, interactively if you want that, and have them still work. iconic behaviour, no notes.

the can_run function can tell you if a certain binary is installed and if so where it lives, whereas the run function can actually execute any of the commands you give it and hand you back a clear return value, all while respecting your verbosity settings. queen behaviour honestly πŸ‘‘


πŸ‘‘ CLASS METHODS πŸ‘‘

⭐ $ipc_run_version = IPC::Cmd->can_use_ipc_run( [VERBOSE] )

utility function that spills whether IPC::Run is available. and if you pass the verbose flag? it will print diagnostic messages when IPC::Run can't be found or loaded. so thoughtful of it 🫢

πŸ’œ $ipc_open3_version = IPC::Cmd->can_use_ipc_open3( [VERBOSE] )

utility function that tells you if IPC::Open3 is available. same deal as above: pass the verbose flag and it'll print diagnostic messages if IPC::Open3 can not be found or loaded. lowkey the same energy, different module. iykyk.

πŸ’… $bool = IPC::Cmd->can_capture_buffer

utility function that tells you if IPC::Cmd is capable of capturing buffers in it's current configuration. yes, "it's" β€” that's the original's grammar, I don't make the rules, I just keep every detail intact periodt.

πŸŽ€ $bool = IPC::Cmd->can_use_run_forked

utility function that tells you if IPC::Cmd is capable of providing run_forked on the current platform. vibe check for your OS basically ✨


more coming bestie, don't go anywhere πŸ’–

✨ FUNCTIONS ✨

πŸ’« $path = can_run( PROGRAM );

can_run takes literally one single argument bestie: the name of a binary you're trying to find. Think of it like the unix binary which, or bash's type command β€” it scans through your PATH looking for the binary you asked for. πŸ‘‘

Unlike which and type though, this function is platform independent and will also work on, say, Win32. So versatile, so iconic. πŸ’…

  • Call it in scalar context and it returns the full path to the binary you asked for if it was found, or undef if it wasn't. πŸ’€
  • Call it in list context and the global variable $INSTANCES is a true value, and it returns a list of the full paths to instances of the binary as found in PATH, or an empty list if it wasn't found at all. ✨

πŸ’« $ok | ($ok, $err, $full_buf, $stdout_buff, $stderr_buff) = run( command => COMMAND, [verbose => BOOL, buffer => \$SCALAR, timeout => DIGIT] );

Okay so run takes 4 arguments, and we're going through each one because I refuse to let you miss a detail, no cap: 🫢

  • command β€” this is the command to execute. It can be either a string or an array reference. This is a required argument, so don't skip it bestie. Also, go read the "Caveats" section for the tea on how commands get parsed and what their limitations are. πŸ“
  • verbose β€” this controls whether all output of a command should also get printed to STDOUT/STDERR, or whether it should only get trapped in buffers. And note: buffers require IPC::Run to be installed, or your system needs to be able to work with IPC::Open3. It defaults to the global setting of $IPC::Cmd::VERBOSE, which by default is 0. 😌
  • buffer β€” this holds all the output of a command. It needs to be a reference to a scalar. Heads up though: this holds both the STDOUT and STDERR messages, and you have absolutely no way of telling which is which. If you need that distinction, run the run command in list context and inspect the individual buffers instead. And of course, this requires that the underlying call supports buffers β€” see the note on buffers up above. πŸ™ˆ
  • timeout β€” sets the maximum time the command is allowed to run before aborting, using the built-in alarm() call. If the timeout gets triggered, the errorcode in the return value will be set to an object of the IPC::Cmd::TimeOut class. Check the "error message" section below for the details. Defaults to 0, meaning no timeout is set. ⏰

run will return a simple true or false when called in scalar context. In list context, you get back a list of the following items:

  • success β€” a simple boolean indicating whether the command executed without errors or not.
  • error message β€” if the first element of the return value (success) was 0, then some error happened. This second element is the error message the command you requested exited with, if available. It's generally a pretty printed value of $? or $@. See perldoc perlvar for the details on what those can contain. And if the error was a timeout, the "error message" will be prefixed with the string IPC::Cmd::TimeOut, the timeout class. πŸ‘€
  • full_buffer β€” an array reference containing all the output the command generated. Note: buffers are only available if you have IPC::Run installed, or if your system is able to work with IPC::Open3 β€” see below. Otherwise, this element will be undef. πŸ’€
  • out_buffer β€” an array reference containing all the output sent to STDOUT that the command generated. The notes from full_buffer apply here too.
  • error_buffer β€” an array reference containing all the output sent to STDERR that the command generated. Same deal, the notes from full_buffer apply.

Also go peek at the "HOW IT WORKS" section below to see how IPC::Cmd decides what modules or function calls to use when issuing a command. 🧚


πŸ’« $hashref = run_forked( COMMAND, { child_stdin => SCALAR, timeout => DIGIT, stdout_handler => CODEREF, stderr_handler => CODEREF} );

run_forked is used to execute some program or a coderef, optionally feed it some input, and get its return code and output (both stdout and stderr into separate buffers). On top of that, it lets you terminate the program if it takes too long to finish. πŸ”₯

The important and distinguishing feature of run_forked is the execution timeout, which at first seems like a pretty simple task β€” but bestie, if you think about how the program you're spawning might spawn some children itself (which in their turn could do the same, and so on and so on)… yeah, it turns out to not be a simple issue at all. 😭

run_forked is designed to survive and successfully terminate almost any long running task β€” even a fork bomb, as long as your system has the resources to survive during the given timeout. It really said "not today". πŸ‘‘

This is achieved by creating a separate watchdog process which spawns the specified program in a separate process session and supervises it: optionally feeding it input, storing its exit code, stdout and stderr, and terminating it in case it runs longer than specified. Main character energy fr fr. ✨

Invocation requires the command to be executed or a coderef, and optionally a hashref of options:

🌸 "timeout"

Specify in seconds how long to run the command before it gets killed with SIG_KILL (9), which effectively terminates it and all of its children (direct or indirect). πŸ’€

🌸 "child_stdin"

Specify some text that will be passed into the STDIN of the executed program. πŸ“

🌸 "stdout_handler"

Coderef of a subroutine to call when a portion of data is received on STDOUT from the executing program.

🌸 "stderr_handler"

Coderef of a subroutine to call when a portion of data is received on STDERR from the executing program.

🌸 "wait_loop_callback"

Coderef of a subroutine to call inside of the main waiting loop (while run_forked waits for the external to finish or fail). It's useful to stop a running external process before it ends by itself, like:

  my $r = run_forked("some external command", {
          'wait_loop_callback' => sub {
          if (condition) {
              kill(1, $$);
          }
          },
          'terminate_on_signal' => 'HUP',
          });

Combined with stdout_handler and stderr_handler, this lets you terminate an external command based on its output. It could also be used as a timer without engaging with alarm (signals). 🧚

Remember that this code could be called every millisecond (depending on the output which the external command generates), so try to make it as lightweight as possible. Not the moment for your heavy lifting bestie!!

🌸 "discard_output"

Discards the buffering of the standard output and standard errors for return by run_forked(). With this option you have to use the std*_handlers to read what the command outputs. Useful for commands that send a lot of output. 🌈

🌸 "terminate_on_parent_sudden_death"

Enable this option if you wish all spawned processes to be killed if the initially spawned process (the parent) is killed or dies without waiting for child processes. Dramatic name, extremely fair request. πŸ’…

run_forked will return a HASHREF with the following keys:

🌸 "exit_code"

The exit code of the executed program.

🌸 "timeout"

The number of seconds the program ran for before being terminated, or 0 if no timeout occurred.

🌸 "stdout"

Holds the standard output of the executed command (or an empty string if there was no STDOUT output, or if discard_output was used; it's always defined!). 🫢

🌸 "stderr"

Holds the standard error of the executed command (or an empty string if there was no STDERR output, or if discard_output was used; it's always defined!). 🫢

🌸 "merged"

Holds the standard output and error of the executed command merged into one stream (or an empty string if there was no output at all, or if discard_output was used; it's always defined!). 🫢

🌸 "err_msg"

Holds some explanation in the case of an error.


πŸ’« $q = QUOTE

Returns the character used for quoting strings on this platform. This is usually a ' (single quote) on most systems, but some systems use different quotes. For example, Win32 uses " (double quote). The more you know. ⭐

You can use it like this:

  use IPC::Cmd qw[run QUOTE];
  my $cmd = q[echo ] . QUOTE . q[foo bar] . QUOTE;

This makes sure that foo bar is treated as a string, rather than two separate arguments to the echo function. Periodt. πŸ’…


✨ HOW IT WORKS ✨

So run will try to execute your command using the following logic, in order, bestie:

  • If you have IPC::Run installed, and the variable $IPC::Cmd::USE_IPC_RUN is set to true (see the "Global Variables" section), use that to execute the command. You'll have the full output available in buffers, interactive commands are sure to work, and you're guaranteed to have your verbosity settings honored cleanly. Slay. πŸ‘‘
  • Otherwise, if the variable $IPC::Cmd::USE_IPC_OPEN3 is set to true (see the "Global Variables" section), try to execute the command using IPC::Open3. Buffers will be available on all platforms, interactive commands will still execute cleanly, and also your verbosity settings will be adhered to nicely. πŸ’–
  • Otherwise, if you have the verbose argument set to true, we fall back to a simple system() call. We cannot capture any buffers this way, but interactive commands will still work.
  • Otherwise we will try and temporarily redirect STDERR and STDOUT, do a system() call with your command, and then re-open STDERR and STDOUT. This is the method of last resort, and it will still allow you to execute your commands cleanly. However, no buffers will be available. 😭

✨ Global Variables ✨

The behaviour of IPC::Cmd can be altered by changing the following global variables:

🌈 $IPC::Cmd::VERBOSE

This controls whether IPC::Cmd will print any output from the commands to the screen or not. The default is 0.

🌈 $IPC::Cmd::USE_IPC_RUN

This variable controls whether IPC::Cmd will try to use IPC::Run when available and suitable.

🌈 $IPC::Cmd::USE_IPC_OPEN3

This variable controls whether IPC::Cmd will try to use IPC::Open3 when available and suitable. Defaults to true. βœ…

🌈 $IPC::Cmd::WARN

This variable controls whether run-time warnings should be issued, like the failure to load an IPC::* module you explicitly requested.

Defaults to true. Turn this off at your own risk. 😬

🌈 $IPC::Cmd::INSTANCES

This variable controls whether can_run will return all instances of the binary it finds in the PATH when called in a list context.

Defaults to false, set to true to enable the described behaviour. 🌟

🌈 $IPC::Cmd::ALLOW_NULL_ARGS

This variable controls whether run will remove any empty/null arguments it finds in command arguments.

Defaults to false, so it will remove null arguments. Set it to true to allow them. πŸ“

🚨 Caveats 🚨

okay bestie, sit down, grab a snack, because this is the part where we talk about the gotchas. no cap, these are real, and they will absolutely humble you if you don't read them πŸ’€


Whitespace and IPC::Open3 / system() 🫧

so when you're using IPC::Open3 or system, and you hand over a string as your command argument, IPC::Cmd trusts that you already escaped it properly. periodt. you can use the QUOTE constant as a portable quote character (peep that in the section above πŸ‘€).

<b>but</b> β€” and this is the plot twist β€” if you pass an array reference instead, the rules change completely:

  • if your command has special characters in it (< > | &), it gets internally stringified before running. why? so those special characters keep their ✨special meaning✨ instead of being escaped and passed along as boring old arguments.
  • but then, plot twist the second: if your command had arguments with whitespace inside them, stringifying the whole thing would lose the significance of that whitespace 😭. so IPC::Cmd will quote any arguments containing whitespace in your command β€” but only if the command was passed as an arrayref and it contains special characters.

Whitespace and IPC::Run πŸŒ€

with IPC::Run, if you pass a string as the command argument, the string gets split on whitespace to figure out the individual elements of your command. usually this just Does What You Mean and everything's fine πŸ’….

but it can break if you have files or commands with whitespace in them. πŸ™ˆ

if you do <b>not</b> want that to happen, pass an array reference instead, where all the parts of your command are already separated out. heads up though: if there's extra or spurious whitespace in those parts, the parser or the underlying code may not interpret it correctly, and that's an error. 😭

example time, bestie. this code right here:

gzip -cdf foo.tar.gz | tar -xf -

should be passed either as

"gzip -cdf foo.tar.gz | tar -xf -"

or as

['gzip', '-cdf', 'foo.tar.gz', '|', 'tar', '-xf', '-']

but be so careful not to pass it like, for example,

['gzip -cdf foo.tar.gz', '|', 'tar -xf -']

because that will lead to exactly the issues we just described above. do not do this. i'm literally begging 🫢


IO Redirect πŸ”€

right now it's too complicated to parse your command for IO redirections. lowkey tragic, i know.

for capturing STDOUT or STDERR there's a work around though β€” you can just inspect your buffers for the contents. slay ✨


Interleaving STDOUT/STDERR πŸ˜΅β€πŸ’«

so neither IPC::Run nor IPC::Open3 can interleave STDOUT and STDERR. neither of them. not a one.

for short bursts of output from a program, like this sample:

for ( 1..4 ) {
    $_ % 2 ? print STDOUT $_ : print STDERR $_;
}

IPC::[Run|Open3] will first read all of STDOUT, then all of STDERR. meaning the output looks like '13' on STDOUT and '24' on STDERR, instead of

1
2
3
4

this has been recorded in rt.cpan.org as bug #37532: Unable to interleave STDOUT and STDERR. πŸ“ iconic of it to be documented, honestly.


πŸ‘€ See Also

IPC::Run, IPC::Open3


πŸ’– ACKNOWLEDGEMENTS πŸ’–

thanks to James Mastros and Martijn van der Streek for their help in getting IPC::Open3 to behave nicely 🫢 absolute legends.

thanks to Petya Kohts for the run_forked code. king behavior πŸ‘‘


πŸ› BUG REPORTS

please report bugs or other issues to <bug-ipc-cmd@rt.cpan.org>. do it, bestie, don't be shy πŸ’Œ


πŸ‘‘ AUTHOR

original author: Jos Boumans <kane@cpan.org>. current maintainer: Chris Williams <bingos@cpan.org>.


this library is free software; you may redistribute and/or modify it under the same terms as Perl itself. free as in go off πŸ’…


and that's a wrap on IPC::Cmd(3perl) from perl v5.44.0, dated 2026-10-17 β€” you're officially a shell-quoting girlie now, go forth and pass those arrayrefs correctly πŸ”₯πŸ’–βœ¨

πŸ“¦ where this page comes from
  • arch rolling: perl 5.44.0-1 Β· Artistic-1.0-Perl AND GPL-1.0-or-later
  • πŸ’– girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms