How to escape strings for terminal in Ruby?

后端 未结 2 1127
长发绾君心
长发绾君心 2020-12-29 04:10

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         


        
相关标签:
2条回答
  • 2020-12-29 04:47

    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.

    0 讨论(0)
  • 2020-12-29 04:58

    Please never use the "single command line" form of exec, that leaves you open to all the usual quoting and injection issues and pointlessly launches a shell. From the fine manual:

    exec(cmdname, arg1, ...)

    command name and one or more arguments (no shell)

    So instead of mucking around with quoting and escaping and what not, just use the shell-less version:

    exec '/usr/bin/mplayer', song.file
    

    and bypass the shell completely. Similarly for system.

    0 讨论(0)
提交回复
热议问题