Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much

How to run a shell script from a Perl program?

by Anonymous Monk
on May 07, 2001 at 19:07 UTC ( #78523=categorized question: print w/replies, xml ) Need Help??
Contributed by Anonymous Monk on May 07, 2001 at 19:07 UTC
Q&A  > programs and processes

Answer: How to run a shell script from a Perl program?
contributed by radiantmatrix

Perl offers three slightly different mechanisms for executing external commands:

  1. system
  2. exec
  3. Backticks or qx//
  1. Using system

    system($command, @arguments); # For example: system( "sh", "", "--help" ); system("sh --help");
    System will execute the $command with @arguments and return to your script when finished. You may check $! for certain errors passed to the OS by the external application.

    Read the documentation for system for the nuances of how various invocations are slightly different.

  2. Using exec

    This is very similar to the use of system, but it will terminate your script upon execution. Again, read the documentation for exec for more.

  3. Using backticks or qx//

    my $output = ` --option`; my $output = qx/ --option/;
    The backtick operator and it's equivalent qx// excute the command and options inside the operator and return that commands output to STDOUT when it finishes.

There are also ways to run external applications through creative use of open, but this is advanced use; read the documentation for more.

Answer: How to run a shell script from a Perl program?
contributed by snapdragon

The way to do this is to use a systen call to run your script:


However I thought that I'd mention a couple of points to go with this.

  1. Don't assume that your shell environment variables will be kept - a shell script that works fine on the command line may not work when run from Perl
  2. Be careful with your directories - try to make sure you're executing from the right place. It's often worthwhile to do a chdir to the right directory in Perl before calling your script. i.e.  chdir "/path/to/script/";

Good luck!
Answer: How to run a shell script from a Perl program?
contributed by Plankton

I like to do this sometimes ...

my $shell_out = <<`SHELL`; for fs in `/sbin/fdisk -l | grep -v swap | grep Linux | cut -d ' ' -f1 +` do /sbin/e2label \$fs | grep recovery > /dev/null 2>&1 && echo "Y +ES" && exit 0 done echo "NO" exit 0 SHELL
... to capture the stdout of the shell commands in a scalar var.
Answer: How to run a shell script from a Perl program?
contributed by ruzam

A slightly longer version using the exec method with forked pipes (and an optional timeout value).

# two parameters: # cmd - a command or reference to an array of command + arguments # timeout - number of seconds to wait (0 = forever) # returns: # cmd exit status (-1 if timed out) # cmd results (STDERR and STDOUT merged into an array ref) sub ExecCmd { my $cmd = shift || return(0, []); my $timeout = shift || 0; # opening a pipe creates a forked process my $pid = open(my $pipe, '-|'); return(-1, "Can't fork: $!") unless defined $pid; if ($pid) { # this code is running in the parent process my @result = (); if ($timeout) { my $failed = 1; eval { # set a signal to die if the timeout is reached local $SIG{ALRM} = sub { die "alarm\n" }; alarm $timeout; @result = <$pipe>; alarm 0; $failed = 0; }; return(-1, ['command timeout', @result]) if $failed; } else { @result = <$pipe>; } close($pipe); # return exit status, command output return ($? >> 8), \@result; } # this code is running in the forked child process { # skip warnings in this block no warnings; # redirect STDERR to STDOUT open(STDERR, '>&STDOUT'); # exec transfers control of the process # to the command ref($cmd) eq 'ARRAY' ? exec(@$cmd) : exec($cmd); } # this code will not execute unless exec fails! print "Can't exec @$cmd: $!"; exit 1; }
Answer: How to run a shell script from a Perl program?
contributed by DeadPoet

If you want the PID, STDOUT, and STDERR, use IPC::Open3.


use IPC::Open3; local (*IN, *OUT, *ERR); my $pid = eval{ open3( \*IN, \*OUT, \*ERR, 'my_command', 'my_command_args' ); }; if ($@) { warn ($@); } ## capture your output, if needed... ## wait on the pid... wait( $pid, 0 );

Please (register and) log in if you wish to add an answer

  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.
  • Log In?

    What's my password?
    Create A New User
    and the web crawler heard nothing...

    How do I use this? | Other CB clients
    Other Users?
    Others musing on the Monastery: (2)
    As of 2020-10-28 10:54 GMT
    Find Nodes?
      Voting Booth?
      My favourite web site is:

      Results (260 votes). Check out past polls.