Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

perl

system

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".

like image 392
andrewrk Avatar asked Aug 19 '08 23:08

andrewrk


People also ask

What does system () do in Perl?

Perl's system() function executes a system shell command. Here the parent process forks a child process, and then waits for the child process to terminate. The command will either succeed or fail returning a value for each situation.

How do I print a Perl command?

open(F, "ls | tee /dev/tty |"); while (<F>) { print length($_), "\n"; } close(F); This will both print out the files in the current directory (as a consequence of tee /dev/tty ) and also print out the length of each filename read.


2 Answers

Here's an updated execute that will print the results and return them:

sub execute {
  my $cmd = shift;
  print "$cmd\n";
  my $ret = `$cmd`;
  print $ret;
  return $ret;
}
like image 106
andrewrk Avatar answered Oct 14 '22 12:10

andrewrk


Another technique to combine with the others mentioned in the answers is to use the tee command. For example:

open(F, "ls | tee /dev/tty |");
while (<F>) {
    print length($_), "\n";
}
close(F);

This will both print out the files in the current directory (as a consequence of tee /dev/tty) and also print out the length of each filename read.

like image 36
Greg Hewgill Avatar answered Oct 14 '22 13:10

Greg Hewgill