Escaping in ruby system calls

There are several ways to do a system call in ruby. The three most common are:

  • Backticks `…`
  • %x[ … ]
  • system(cmd,[args,…])

You can assign the result of such a call to a variable, e.g.

output = x%[pwd]

If you use special characters like ‘.’ , ‘|’ or ‘\’ they have to be escaped using a backslash before. Consider the following bash command line:

find . -name "*.pat" | xargs grep 'match\|loop' | sed "s/\.\/\(.*\.pat\):.*/\1/" | sort -u

To get the same result in ruby you have to call it like this:

output = %x[find . -name '*.pat' | xargs '/bin/grep' 'match\\\|loop' | sed 's/\\\.\\\/\\\(\.*pat\\\):\.*/\\1/' | sort -u]
This entry was posted in Uncategorized and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.