【问题标题】:Why do I get errors running shell commands in rails console (irb)为什么我在 rails 控制台 (irb) 中运行 shell 命令时出错
【发布时间】:2014-08-25 02:13:26
【问题描述】:

当我从 Rails 控制台运行一个简单的 ls 命令时,我收到了这个错误:

$ rails c
irb(main):001:0> `ls`
script/rails: No such file or directory - ls
=> nil

在使用cd ~ 等其他命令时,我遇到了同样的错误。谁能告诉我为什么不显示当前文件夹的内容?

更新: 在尝试exec('ls') 之后,这是输出,这让我觉得它一定是一些本地设置。

irb(main):001:0> exec('ls')
Errno::ENOENT: No such file or directory - ls
    from (irb):1:in `exec'
    from (irb):1
    from     /[filepath]/runtime/ruby1.9/gems/1.9.1/gems/railties-3.2.18/lib/rails/commands/console.rb:47:in `start'
from /[filepath]/runtime/ruby1.9/gems/1.9.1/gems/railties-3.2.18/lib/rails/commands/console.rb:8:in `start'
from /[filepath]/runtime/ruby1.9/gems/1.9.1/gems/railties-3.2.18/lib/rails/commands.rb:41:in `<top (required)>'
from /[filepath]/runtime/ruby1.9/1.9.1/rubygems/custom_require.rb:36:in `require'
from /[filepath]/runtime/ruby1.9/1.9.1/rubygems/custom_require.rb:36:in `require'
from script/rails:6:in `<main>'

【问题讨论】:

  • 你能在 Ruby 之外运行 ls 吗?
  • 是的,退出控制台后,ls 立即按预期工作。
  • 您查看过PATH 环境变量吗?您是否尝试过使用 ls 的完整路径?
  • 好点。 /bin 在我的 PATH 中,但 /bin/ls 确实适用于 ruby​​ 控制台。谢谢你的建议。请原谅我缺乏知识,但是否有一个单独的路径可以加载我应该更新的轨道?
  • 也许你的 Rails 配置弄乱了路径?我会在 application.rb、environment.rb 和任何初始化程序中寻找线索。还可以考虑取出宝石,尤其是最近添加的宝石。

标签: ruby shell ls rails-console


【解决方案1】:

这是因为您现在实际上是在 ruby​​ on rails 应用程序的上下文中(因此您可以使用类、活动记录模型等)中的交互式 ruby​​ 会话(注意提示中的 irb)。您发出的命令应该是 ruby​​ 命令。原始 shell 命令在这里无法正常工作。

但是你可以使用 exec:

$ rails c
Connecting to database specified by database.yml
Loading development environment (Rails 3.2.17)
2.0.0p247 :001 > exec('ls')
app     config.ru  doc      Gemfile.lock  log       README.rdoc  spec
config  db         Gemfile  lib           Rakefile  script       tmp
16:12:10 durrantm Castle2012 /home/durrantm/Dropnot/_/rails_apps/linker master
$ 

您也可以使用反引号 (`) 来运行命令,即

2.0.0p247 :007 > `ls`
=> "app\nconfig\nconfig.ru\ndb\ndoc\nGemfile\nGemfile.lock\nlib\nlog\nRakefile\nREADME.rdoc\nscript\nspec\ntmp\n" 

还有%x:

2.0.0p247 :020 > %x('ls')
 => "app\nconfig\nconfig.ru\ndb\ndoc\nGemfile\nGemfile.lock\nlib\nlog\nRakefile\nREADME.rdoc\nscript\nspec\ntmp\n" 

system:

2.0.0p247 :021 > system("ls")
app     config.ru  doc      Gemfile.lock  log       README.rdoc  spec
config  db         Gemfile  lib           Rakefile  script       tmp
 => true 

【讨论】:

  • 请看我的更新。我猜是本地配置或环境问题。
  • hmmm,如果你只使用 irb 而不是 rails console 会发生什么?
  • @MichaelDurrant +1 用于系统“ls”。这正是我一直在寻找的。谢谢!