Andrea
Andrea

Reputation: 4503

Exec system command containing a semicolon in Ruby

Seems a silly question, but I'm struggling to find the answer.

I need to execute a really long command directly from ruby code to the shell, and this command has to contain a ; character.

If I try to escape it with \; doesn't work, if I try to substitute it with \%3b it executes but it doesn't substitute %3b with ;, so it doesn't work too.

I tried with exec, system, ` #{str} `, and I can't make it work. It always splits in two my command.

Upvotes: 0

Views: 99

Answers (1)

Gavin Miller
Gavin Miller

Reputation: 43865

You should have no problem placing a semicolon within a shell command as long as you quote it properly:

system('cat file | grep ";"')
# => someline with a ; in it

system("cat #{a_variable} | grep ';'")
# => this will work as well for finding ;

I also find that Open3 module to be a bit easier to use for odder system calls / quoting issues (but it can be a bit difficult to get it working too -- trade offs):

require 'open3'
cmds = %w(grep ';' a_file)
stdout, status = Open3.capture2(*cmds)

Upvotes: 1

Related Questions