確認ダイアログを出しながらディレクトリやファイルを削除するスクリプトを書いた。大したコード書いてないし逆引きRubyに載ってたコードをまるパクリしてるところもあるけど便利だと思う。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "fileutils" | |
dir = Dir::entries(Dir::pwd) | |
dir.each do |d| | |
unless /(^\.|#{__FILE__})/ =~ d | |
f = File::stat(d) | |
puts "#{d} is #{(Time.now - f.mtime).div(24*60*60)} days old." | |
puts "Would you like to remove this file/directory? (y/n)" | |
answer = gets.chomp | |
if answer == "y" | |
if FileTest.file?(d) | |
File::delete(d) | |
else | |
dirlist = Dir::glob(d + "**/").sort { | |
|a,b| b.split('/').size <=> a.split('/').size | |
} | |
dirlist.each {|d| | |
Dir::foreach(d) {|f| | |
FileUtils.rm_rf(d+f) unless (/\.+$/ =~ f) | |
} | |
Dir::rmdir(d) | |
} | |
end | |
else | |
next | |
end | |
end | |
end |
そのディレクトリにあるファイル/ディレクトリ一覧を取得した後、「このファイル/ディレクトリは作られてから何日経っています。削除しますか? (y/n)」というダイアログ(英語)を表示する。y
が入力されると削除を行う。地味に使える。
RubyのFileUtilsはすごく便利だと思う。シェルスクリプトでしこしこ書くのがアホらしくなる。RubyがPerlなみにあらゆるuni*x系のサーバーに入るようになったらさぞかし便利だろうと思う。