in reply to Re: passing string to stdin on exec-command
in thread passing string to stdin on exec-command

my $str = q(Aren't you glad you listened to Abigail and not Roger?); system("echo '$str' | cat"); __output__ sh: -c: line 1: unexpected EOF while looking for matching `'' sh: -c: line 2: syntax error: unexpected end of file
--
3dan

Replies are listed 'Best First'.
Re: passing string to stdin on exec-command
by Abigail-II (Bishop) on Nov 05, 2003 at 14:33 UTC
    And that brings us to the question, how do you escape single quotes in the shell? The answer is not putting a backslash in front of a single quote. In the shell, a backslash does not have a special meaning when it's inside single quotes. But then what?

    The answer lies in the fact that the shell does concatenation by absense of whitespace. So, if we want to put O'Reilly inside quotes, we break the string into three parts: O, ' and Reilly. The first and last part will be surrounded by single quotes, the single quote will be surrounded by double quotes, and then we stick the three parts together, resulting in: 'O'"'"'Reilly'. This sounds complicated, but we can do this with a single substitution: s/'/'"'"'/g.

    #!/usr/bin/perl use strict; use warnings; while (<DATA>) { chomp; my $orig = $_; s/'/'"'"'/g; my $result = `echo '$_' | cat`; chomp $result; print STDERR "Mismatch [$orig] vs [$result]\n" unless $result eq $ +orig; } __DATA__ foo bar 'foo bar' foo'"'bar '''''''''''' ''''''''''' "foo'bar" "foo''bar" "foo'bar"" ' "'"

    Abigail

      And this is why you should be thankful that system() and qx() use only /bin/sh and never "the user's preferred shell", because /bin/csh cannot quote all possible strings. I can't recall the combo you can't get now, but I think it's a backslash followed by a newline that cannot be quoted, because one backslash and a newline just creates a newline, but two backslashes and a newline creates two backslashes and a newline, or something like that.

      -- Randal L. Schwartz, Perl hacker
      Be sure to read my standard disclaimer if this is a reply.

Re: Re: Re: passing string to stdin on exec-command
by Roger (Parson) on Nov 05, 2003 at 14:16 UTC
    Thanks 3dan, very good point ++. Yes you are right. I have forgotten about single quotes in input strings.