Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: sh: -c: line 1: syntax error near unexpected token `|'

by stevieb (Canon)
on May 10, 2012 at 07:49 UTC ( [id://969763]=note: print w/replies, xml ) Need Help??


in reply to sh: -c: line 1: syntax error near unexpected token `|'

Perhaps because your shell is interpreting it literally?

I politely request you show us your actual code. Depending on what you are trying to do, there are glaring changes that can be made.

Replies are listed 'Best First'.
Re^2: sh: -c: line 1: syntax error near unexpected token `|'
by perl@1983 (Sexton) on May 10, 2012 at 08:22 UTC
    That's pretty much the actual code is I'm afraid. Additionally, you can think of $cmd as below:
    $cmd = "------------- Hello World ------------";
      You are using Perl, but your question pertains to the shell that evaluates the command in backticks. To solve this, you have to see, why your shell doesn't like the command.

      Besides take a look at perlop. There is a section about quoting (and you should quote, what you are giving to the shell) stating about the command given in backticks: "How that string gets evaluated is entirely subject to the command interpreter on your system."

      For example, when I try to run your code on my Ubuntu I am getting something like

      #!/usr/bin/perl use strict; use warnings; my $cmd = "------------- Hello World ------------"; my $result = `echo $cmd | grep '\-\-\-\-'`; print $result . "\n";
      grep: unknown option »----«

      I am assuming however, that you don't really want to search a string in Perl that way (there are better ways), but to learn something about calling external commands.

      Probably better to place quotes around the command, for example:
      $cmd = "'------------- Hello World ------------'";
      or use somthing like q()

      Also, you might like to use "end of options":
      my $result = `echo -- $cmd | grep -- '\-\-\-\-'`;

        Regarding quotes, the OP might find a module that provides shell escaping useful. Such as String::ShellQuote.

        printf is probably more surefire than echo there:

        printf "%s" "$cmd" | grep -e '----'

        But shelling out is very error-prone (as the OP discovered) and pretty vain when the code can be reproduced in Perl in a few lines.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://969763]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others wandering the Monastery: (6)
As of 2024-03-28 19:14 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found