对于Ruby CLI,将目录更改为用户root / home目录的最可靠方法是什么?

时间:2013-07-27 22:13:28

标签: ruby command-line-interface

我真的不确定是否要求用户在运行命令之前确保它们在主目录中,如果没有则中止或只是更改它们的目录?

没有参数的

Dir.chdir默认为用户主目录,当块完成后返回上一个目录

Dir.chdir do 
  puts Dir.pwd
end

puts Dir.pwd

# => 'Users/Brian'

# => '/Users/Brian/gems/etc...'

在整个代码中,我需要chdir几次。这很可靠吗?

有人对这种事情的最佳方法有任何见解吗?

1 个答案:

答案 0 :(得分:1)

总结Avdi Grimm's screencast on the same subject

如果您使用的Ruby版本大于1.9,则Dir模块会提供方法#home。但是,这取决于在用户的shell会话上设置的环境变量HOME。要可靠地获取主目录,您应该将当前用户的登录名传递给Dir.home命令。或者,在代码中:

# Works if HOME is set in the environment i.e., if "echo $HOME" returns the home directory
# when that command is run on the command-line
Dir.home     # => /Users/<username>, Works if HOME is set

# If the HOME environment variable is not set, you should explicitly pass in the username
# of the currently logged-in user
Dir.home(username)     # => /Users/<username>

# The current username can be obtained using
username = `whoami`

# or

require 'etc'
username = Etc.getlogin

现在进行最后的警告:这适用于* nix。

相关问题