使用ruby创建符号链接

时间:2015-12-01 09:54:25

标签: ruby ubuntu symlink

我正在尝试为创建的文件创建一个符号链接,但是我收到类似File exists - (/etc/nginx/sites-available/sushant.com, /etc/nginx/sites-enabled/sushant.com) (Errno::EEXIST)的错误

这是我的代码

    require 'fileutils'
open('/etc/hosts') do |f|
  matches = []
  vhosts = []
  f.readlines.each do |lines|
    matches << lines if lines =~ /.*.com/
  end
  matches.each do |val|
    val.split.each do |x|
      vhosts << x if x =~ /.*.com/
    end
  end
  vhosts.each do |domain|
#put the path to sites-enabled
    unless File.file? "/etc/nginx/sites-available/#{domain}"
      open("/etc/nginx/sites-available/#{domain}", 'w') do |g|
        g << "server { \n"
        g << "\tlisten 80 default_server;\n"
        g << "\tlisten [::]:80 default_server ipv6only=on;\n"
        g << "\troot /usr/share/nginx/html;\n"
        g << "\tindex index.html index.htm;\n"
        g << "\tserver_name localhost;\n"
        g << "\tlocation / {\n"
        g << "\t\ttry_files $uri $uri/ =404;\n"
        g << "\t}\n"
        g << "}\n"
        g << "server {\n"
        g << "\tpassenger_ruby /path/to/ruby;\n"
        g << "\trails_env development;\n"
        g << "\tlisten 80;\n"
        g << "\tserver_name #{domain};\n"
        g << "\troot /usr/share/nginx/html/#{domain}/public;\n"
        g << "\tpassenger_enabled on;\n"
        g << "}\n"
      end
      File.symlink  "/etc/nginx/sites-available/#{domain}", "/etc/nginx/sites-enabled/#{domain}"
    end
  end

  p vhosts
end

运行脚本后,为什么会出现EEXIST错误?我错过了什么吗?

1 个答案:

答案 0 :(得分:1)

我发现我应该首先放置File.symlink "/etc/nginx/sites-available/#{domain}", "/etc/nginx/sites-enabled/#{domain}"然后放置创建文件的操作。