keifer
keifer

Reputation: 155

How to grab the Unix command that I had run using Perl script?

As I am still new to Unix and Perl, I'm finding a simple and direct method to grab the Unix command that I had run using Perl script.

What I know is "history" can track back the commands that I had run, but it is not working in Perl using back ticks history to run it.

I tried to put "history > filename" in vi text editor in a temporary file, use command "source" it, and it works, but command "source" also not working in Perl script using back ticks.

Can anyone guide me about my problems? direct me to correct method to solve my problems? T.T

Thanks.

Upvotes: 1

Views: 633

Answers (3)

djhaskin987
djhaskin987

Reputation: 10057

If you have access to the perl script (that is, you can change it), you can simply write each command run in the perl script to a chosen text file:

sub run_program 
{
    my $program = shift;
    open PROGS, ">>my-commands.txt", or die $!;
    print PROGS $program."\n";
    `$program`;
    close(PROGS);
}

then just run `run_program($command) every time you wish to run a command in the script.

Upvotes: 0

Edoardo Pirovano
Edoardo Pirovano

Reputation: 8334

This will get the history of commands that were run by the user in interactive mode:

$data_file = "~/.bash_history";
open(DAT, $data_file) || die("Could not open file!");
@fileData = <DAT>;
close(DAT);
foreach $command (@fileData) {
    # Do things here.
}

As mentioned by Wobble, though, this history file will not include commands run from a Perl script - you'll have to have the script append the command to a file when it runs it, thus creating it's own history file (or, append it to ~/.bash_history, which will have it share the history file with interactive shells).

Upvotes: 0

Wooble
Wooble

Reputation: 89877

You can't. Shells (well, bash and tcsh, anyway, your shell might, but probably doesn't, vary) only save command history in interactive mode. Commands run in a subshell by a perl script won't be added to the history file.

Upvotes: 4

Related Questions