Skip to content

Instantly share code, notes, and snippets.

@RobertAudi
Created October 27, 2010 14:34
Show Gist options
  • Save RobertAudi/649132 to your computer and use it in GitHub Desktop.
Save RobertAudi/649132 to your computer and use it in GitHub Desktop.
Extract one or multiple archives of any type
#!/usr/bin/env ruby
# check if a command exists
def command_exists?(command)
system("which #{command} > /dev/null 2>/dev/null")
$?.exitstatus == 0
end
def usage
usage = "Usage: extract [-vz] <file> [<file> <file> ..]\n\n"
usage << "-v\tVerbose output. This option doesn't work will all the archive types\n"
end
def extract(file, verbose = false)
parts = file.split('.')
extension = parts.pop
if (extension == "gz" || extension == "bz2") && parts.last == "tar"
extension = parts.pop + "." + extension
end
case extension
when "tar.gz", "tgz"
command = verbose ? "tar xvzf" : "tar xzf"
system("#{command} #{file}") if command_exists?("tar")
when "tar.bz2", "tbz2"
command = verbose ? "tar xvjf" : "tar xjf"
system("#{command} #{file}") if command_exists?("tar")
when "tar"
command = verbose ? "tar xvf" : "tar xf"
system("#{command} #{file}") if command_exists?("tar")
when "bz2"
command = verbose ? "bunzip2 -v" : "bunzip2"
system("#{command} #{file}") if command_exists?("bunzip2")
when "rar"
system("unrar #{file}") if command_exists?("unrar")
when "gz"
command = verbose ? "gunzip -v" : "gunzip"
system("#{command} #{file}") if command_exists?("gunzip")
when "zip"
command = verbose ? "unzip" : "unzip -q"
system("#{command} #{file}") if command_exists?("unzip")
when "Z"
system("uncompress #{file}") if command_exists?("uncompress")
when "7z"
system("7z x #{file}") if command_exists?("7z")
else
false
end
end
# ------------------------------------------------------------------------
extracted_file_list = []
if ARGV.empty?
print usage
else
# parse options
verbose = ARGV.include?("-v")
ARGV.delete("-v")
ARGV.each do |file|
if File.file?(file)
sucess = extract file, verbose
if sucess
extracted_file_list << file
else
puts "#{file} cannot be extracted using this script..."
end
elsif File.directory?(file)
puts "#{file} is a directory not an archive..."
end
end
end
# Show a nice exit message with the list of extracted archives
unless extracted_file_list.empty?
puts "\nThe following archives have been extracted successfully:"
extracted_file_list.each do |archive|
puts "\t#{archive}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment