红宝石逃生ARGV参数或字符串作为参数传递给shell命令 [英] Ruby escape ARGV argument or string as argument to shell command

查看:217
本文介绍了红宝石逃生ARGV参数或字符串作为参数传递给shell命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

确定这是推动我疯了:

 `LS#{/媒体/音乐/ Miles Davis的}`

失败,因为万里行和戴维斯

之间的空间

说我写一个Ruby脚本和用户通过文件路径作为参数。我如何逃避它喂到一个shell-out命令。是的,是的,我知道,应该避免脱壳而出。但是,这是一个人为的例子,我还需要这一点。

我会做系统(LS,ARGV [0]),但它不返回LS的标准输出输出作为一个字符串,这是反引号做的很好。

如何逃生无论你在shellout插入?


<的div类=h2_lin>解决方案

使用要求'shellwords' Shellwords.escape ,这将解决这种东西给你:

<一个href=\"http://apidock.com/ruby/Shellwords/shellescape\">http://apidock.com/ruby/Shellwords/shellescape

Ok this is driving me crazy:

`ls #{"/media/music/Miles Davis"}`

fails because of the space between "Miles" and "Davis"

Say I write a ruby script and a user passes file path as an argument. How do I escape it and feed to a shell-out command. Yes, yes, I know, shelling out should be avoided. But this is a contrived example, I still need this.

I would do system("ls", ARGV[0]), but it doesn't return the stdout output of ls as a string, which is what backticks do well.

How do escape whatever you insert in a shellout?

解决方案

Use require 'shellwords' and Shellwords.escape, which will fix this sort of stuff for you:

http://apidock.com/ruby/Shellwords/shellescape

这篇关于红宝石逃生ARGV参数或字符串作为参数传递给shell命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆