Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape strings for terminal in Ruby?

I am attempting to start mplayer. My filename contains spaces and these should be escaped. This is the code I am using:

@player_pid = fork do    exec "/usr/bin/mplayer #{song.file}" end 

where #{song.file} contains a path like "/home/example/music/01 - a song.mp3". How can I escape this variable properly (and possible other weird characters that the title may contain) so the terminal will accept my command?

like image 311
xorinzor Avatar asked Jul 04 '13 18:07

xorinzor


People also ask

How do you escape a string in Ruby?

When using strings in Ruby, we sometimes need to put the quote we used to define the string inside the string itself. When we do, we can escape the quote character with a backslash \ symbol.

How do you escape a string?

\ is a special character within a string used for escaping. "\" does now work because it is escaping the second " . To get a literal \ you need to escape it using \ .

How do you escape a string in a shell?

Escape characters. Escape characters are used to remove the special meaning from a single character. A non-quoted backslash, \, is used as an escape character in Bash. It preserves the literal value of the next character that follows, with the exception of newline.

What does string escape mean?

Escaping a string means to reduce ambiguity in quotes (and other characters) used in that string. For instance, when you're defining a string, you typically surround it in either double quotes or single quotes: "Hello World."


1 Answers

Shellwords should work for you :)

exec "/usr/bin/mplayer %s" % Shellwords.escape(song.file) 

In ruby 1.9.x, it looks like you have to require it first

require "shellwords" 

But in ruby 2.0.x, I didn't have to explicitly require it.

like image 58
Mulan Avatar answered Oct 01 '22 02:10

Mulan