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

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

Replies are listed 'Best First'.
•Re: Re: passing string to stdin on exec-command
by merlyn (Sage) on Nov 05, 2003 at 16:48 UTC
    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.