Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris

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

by perl@1983 (Sexton)
on May 10, 2012 at 07:14 UTC ( #969760=perlquestion: print w/replies, xml ) Need Help??

perl@1983 has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks, What can be the reason that I get "sh: -c: line 1: syntax error near unexpected token `|'" error while including below in my Perl code?
`echo $cmd | grep '\-\-\-\-'`
Note: $cmd is a string that contains '------' pattern. Thanks in advance.

Replies are listed 'Best First'.
Re: sh: -c: line 1: syntax error near unexpected token `|'
by stevieb (Canon) on May 10, 2012 at 07:49 UTC

    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.

      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 -- '\-\-\-\-'`;
Re: sh: -c: line 1: syntax error near unexpected token `|'
by Anonymous Monk on May 10, 2012 at 20:06 UTC

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://969760]
Approved by marto
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (3)
As of 2022-07-04 11:59 GMT
Find Nodes?
    Voting Booth?

    No recent polls found