Error running Unix command from Perl

202 Views Asked by At

I am trying to redirect the output and error to a file in Unix through a Perl script.

The command is running fine in Unix, but while running the Perl script it is throwing the error sh: & is unexpected. I tried using escape character also

Command:

`ls -lrt $myfile >>& $output`

Also used Command:

`ls -lrt $myfile >> $output 2>&1` - got ambiguous output redirect error
2

There are 2 best solutions below

16
On

Backticks use /bin/sh. You're trying to redirect STDOUT and STDERR? The syntax is:

>$output 2>&1

You also need to convert your file names to shell literals. They might contain spaces, for example, or worse.

use String::ShellQuote qw( shell_quote );

my $cmd = shell_quote('ls', '-lrt', $myfile);
$cmd .= '>'.shell_quote($output).' 2>&1';
`$cmd`
0
On

Try this and make sure myfile and output have values

$myfile='src';
$output='myoutput';
`ls -lrt $myfile >> $output 2>&1`;