1

I am hitting one issue after another with Ruby, single quote and double quotes today.

I have this Ruby oneliner that was used to detect whether a multiline strings exist within a file.

ruby -e 'exit(gets(nil) =~ %r{${line}} ? 0 : 1)' ${file}

It works fine until when my $line contains a single quote such as

ruby -e 'exit(gets(nil) =~ %r{This is David's car\nMazda 3\n} ? 0 : 1)' /tmp/bug8164
-bash: syntax error near unexpected token `)'

I tried to escape the single quote to the following but no luck.

ruby -e 'exit(gets(nil) =~ %r{This is David\'s car\nMazda 3\n} ? 0 : 1)' /tmp/bug8164
-bash: syntax error near unexpected token `)'

Any idea or thought? Thanks

eugen
  • 8,916
  • 11
  • 57
  • 65
beyonddc
  • 1,246
  • 3
  • 13
  • 26

1 Answers1

3

The problem has nothing to do with Ruby. The problem is bash (as the error message plainly informs you).

Everything on the command line must be a "word" (I'm not sure what the term for it is). Your words are

ruby 
-e 
'thing in single quotes'
${file}

You can't have a single quote inside the thing in single quotes. Period. There is no "escaping" your way out of that rule. (Ruby has escaping of a single quote in single-quoted strings. But you are not writing Ruby. You're writing a shell command.)

To see that this is so, try saying at the command line

$ echo 'exit(gets(nil) =~ %r{This is David's car\nMazda 3\n} ? 0 : 1)'

You will see that you get exactly the same error even though there is no ruby in the story. Escaping the single quote within the single quoted expression won't help.

Consider double-quoting that expression. Consider also learning about the command line and the quoting rules. Or how about writing and running a ruby script, thus preventing the confusion of having to write in two languages at once?

matt
  • 515,959
  • 87
  • 875
  • 1,141