Search code examples
perlsystem

How can Perl's system() print the command that it's running?


In Perl, you can execute system commands using system() or `` (backticks). You can even capture the output of the command into a variable. However, this hides the program execution in the background so that the person executing your script can't see it.

Normally this is useful but sometimes I want to see what is going on behind the scenes. How do you make it so the commands executed are printed to the terminal, and those programs' output printed to the terminal? This would be the .bat equivalent of "@echo on".


Solution

  • As I understand, system() will print the result of the command, but not assign it. Eg.

    [daniel@tux /]$ perl -e '$ls = system("ls"); print "Result: $ls\n"'
    bin   dev  home  lost+found  misc  net  proc  sbin     srv  System  tools  var
    boot  etc  lib   media       mnt   opt  root  selinux  sys  tmp     usr
    Result: 0
    

    Backticks will capture the output of the command and not print it:

    [daniel@tux /]$ perl -e '$ls = `ls`; print "Result: $ls\n"'
    Result: bin
    boot
    dev
    etc
    home
    lib
    

    etc...

    Update: If you want to print the name of the command being system() 'd as well, I think Rudd's approach is good. Repeated here for consolidation:

    sub execute {
        my $cmd = shift;
        print "$cmd\n";
        system($cmd);
    }
    
    my $cmd = $ARGV[0];
    execute($cmd);