0

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
  • 1
    What are you trying to accomplish? There's a very good chance that what you're trying to do is best done natively in perl anyway. Commented Dec 8, 2014 at 15:24
  • I am trying to redirect the output & error of a unix command into a file inside a perl script Commented Dec 8, 2014 at 15:42

2 Answers 2

1

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`
Sign up to request clarification or add additional context in comments.

16 Comments

this is not working I tried. It is throwing "ambiguous output redirect".
When using backticks?
No, /bin/sh is not /bin/csh.
Why you are talking about bash and csh??? The question is about backticks in Perl, and it uses /bin/sh. I really don't care what results in you got in csh or bash. Stop saying the solution gives an error when you haven't even tried it yet.
thanks. so is there any way to run the same command in csh or tcsh or force it execute those command using sh/ksh shell ?
|
0

Try this and make sure myfile and output have values

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.