为什么我在rails console(irb)中运行shell命令时出错

时间:2014-07-03 20:03:45

标签: ruby shell ls rails-console

当我从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>'

1 个答案:

答案 0 :(得分:1)

这是因为您现在实际上处于上下文中的交互式ruby会话(注意提示中的irb)(因此您可以使用ruby的类,活动记录模型等)应用。您发出的命令应该是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
$ 

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

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