【问题标题】:Recursive chmod in ruby on mac OS X?mac OS X上的ruby中的递归chmod?
【发布时间】:2009-10-14 19:00:12
【问题描述】:

我需要删除一个应用程序 (MyApp.app),该应用程序在其所有随附文件夹中具有只读权限。在我删除它之前,我应该将所有包含的文件/目录的权限更改为 0644。如何递归执行此操作?

我试过了

begin; FileUtils.chmod(0644, '#{config.appPath}'); rescue; end
begin; FileUtils.rm_r('#{config.appPath}'); rescue; end

但是FileUtils.chmod 不能递归工作。我不能使用 Unix 命令 - 它必须是 Ruby。

编辑:我不能在当前上下文中使用 Unix 命令。好的,这是一个 RubyCocoa 应用程序,您看到的源代码是 ruby​​ 脚本的一部分,它应该卸载应用程序(请不要对此发表评论,因为这是我的客户拥有的代码)。卸载包括删除应用程序的所有痕迹、终止进程并最终删除应用程序本身。通常它可以工作,但在 MyApp.app 文件夹由于某种原因获得只读权限的情况下不起作用。所以我想在文件夹上递归运行 chmod 并将其删除,但由于某种原因,它在 Ruby 中并不直接。 这就是我寻求帮助的原因。有很多关于如何从命令行执行的示例,但是如何从代码中执行呢?

这里有更多的代码,只是为了展示它是如何实现的:

code =<<FOO
require 'fileutils'
# kill the app before deleting files in case it writes files on exit
%x{/bin/kill -9 #{NSProcessInfo.processInfo.processIdentifier}}
begin; FileUtils.chmod(0644, '#{TBConfig.appPath}'); rescue; end
begin; FileUtils.rm_r('#{TBConfig.appPath}'); rescue; end
FOO
    ff = Tempfile.new('timebridge')
    ff.write(code)
    ff.close
    %x{/usr/bin/ruby #{ff.path}}

再次感谢。

【问题讨论】:

  • 如果还是删了,改权限有什么用?
  • 当你说你不能使用Unix命令时,我很困惑。你在 OSX 上。 Unix 命令在那里工作得很好。这是作业吗? (除此之外,Jeff 是对的:没有理由更改您将要删除的内容的权限。)
  • 如果 MyApp.app 对所有包含的文件夹具有只读权限,我无法删除它。请参阅编辑以获得更好的解释。不,这不是作业......

标签: ruby recursion macos chmod


【解决方案1】:

FileUtils.chmod_R 应该这样做

http://www.ruby-doc.org/core/classes/FileUtils.html#M004351

-- 编辑--

seth@oxygen ~ $ mkdir -p foo/bar/seth

seth@oxygen ~ $ ls -ld foo
drwxr-xr-x  3 seth  staff  102 Oct 15 19:24 foo

seth@oxygen ~ $ ls -ld foo/bar
drwxr-xr-x  3 seth  staff  102 Oct 15 19:24 foo/bar

seth@oxygen ~ $ ls -ld foo/bar/seth
drwxr-xr-x  2 seth  staff  68 Oct 15 19:24 foo/bar/seth

seth@oxygen ~ $ cat test.rb
require 'fileutils'
begin; FileUtils.chmod_R(0777, 'foo'); rescue; end

seth@oxygen ~ $ ruby test.rb

seth@oxygen ~ $ ls -ld foo
drwxrwxrwx  3 seth  staff  102 Oct 15 19:24 foo

seth@oxygen ~ $ ls -ld foo/bar
drwxrwxrwx  3 seth  staff  102 Oct 15 19:24 foo/bar

seth@oxygen ~ $ ls -ld foo/bar/seth
drwxrwxrwx  2 seth  staff  68 Oct 15 19:24 foo/bar/seth

快速测试似乎有效。

【讨论】:

  • 由于某种原因它不会递归地这样做。
  • 我一定会做同样的测试。会让你知道。谢谢
  • @Seth,非常感谢,它成功了!出于某种原因,当我尝试它时它没有,但可能我没有正确使用它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-17
  • 1970-01-01
  • 1970-01-01
  • 2012-06-08
  • 1970-01-01
  • 2013-10-29
相关资源
最近更新 更多