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.

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

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.