C. Monster C. Monster - 2 years ago 86
Perl Question

Running a shell command in a perl loop, using a variable from the perl loop

I received some commands from a website that are really specific and need to be run in the shell

Is there a way to do something like

for my $i (0..9) {
`shellCommand($i)` #ex. echo $i


Here is my MCVE

for my $i (0..9) {
`echo $i`;

should produce the output


Answer Source

You can do it in several ways, depending on what exactly is needed. Error handling and interrogation is yet another aspect of it. Generally, this would involve using system, qx (backticks), or open. See links below. If commands are built at runtime, please be very careful. See note at the end.

If you need output from the command

for my $i (0..9) {
    my $cmd = "shellCommand($i)";
    my $cmdout = qx($cmd);

Depending on what your command is you may have to pay close attention to how to quote it correctly. If you want to get the command's STDERR as well use

my $cmd = "shellCommand($i) 2>&1";

If you don't care for the output why not use system

for my $i (0..9) {
    my $cmd = "shellCommand($i)";
    my $ret = system($cmd);
    if ($ret != 0) {
        warn "Error running $cmd -- ";
        # interrogate further, see documentation for 'system'

See system and qx in perlop. Finally, you can use various forms of open to run a process. For example, see it in perlfaq8, along with a full review of what you are asking.

Note that you can have the command be executed via the shell or not (but via execvp) depending on the exact invocation, see the docs. Also note that the above all block (do not return control before completing), so the script continues only after they're done. This seems to be what you want.

If these commands are meant to be received at runtime you'll need to be very careful and I would in priniciple advise against it. It is very hard to programmatically ensure that an arbitrary string is a safe command to run. If arguments are built at runtime that, again, is a whole separate problem.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download