Ruby sample scripts - file operations

calc-dir-size.rb

#!/usr/bin/env ruby
size = 0
Dir.open(ARGV[0]).each { |file| size += File.size? ARGV[0] + "/" + file }
puts size


calc-dir-size.sh
#!/bin/bash
SIZE=0
DIR=$1

for file in $DIR/*
do
   ((SIZE+=$(stat -c "%s" "$file")))  
done
echo $SIZE


calc-dir-size2.rb
#!/usr/bin/env ruby
# Run as below:
# ls -l /bin | ruby calc-dir-size2.rb

total = 0
STDIN.read.each {|line| total += line.split(" ")[4].to_i }
puts total


calc-dir-size2.sh
#!/bin/sh
DIR=$1

expr $(ls -l $DIR | sed 's/ \+/ /g' | cut -f5 -d' ' | xargs | sed 's/ / + /g')


calc-dir-size3.sh
#!/bin/sh
DIR=$1
ls -l $DIR | awk '{ total += $5 } END { print total }'



check-file.rb
#!/usr/bin/env ruby
if ARGV.length  "exists",
  :file?       => "is a regular file",
  :directory?  => "is a directory",
  :symlink?    => "is a symbolic link",
  :blockdev?   => "is a block device file",
  :chardev?    => "is a character device file",
  :pipe?       => "is a FIFO file",
  :socket?     => "is a UNIX socket file",
  :readable?   => "is readable",
  :writable?   => "is writable",
  :executable? => "is executable/searchable",
  :setuid?     => "has set-UID bit set",
  :setgid?     => "has set-GID bit set",
  :sticky?     => "has sticky bit set",
  :owned?      => "is owned by current effective user",
  :grpowned?   => "is owned by current effective group",
  :zero?       => "is an empty file"
}

file_methods.each {|method, message| puts "File #{file} #{message}" if File.send method, file }




chmod.rb
#!/usr/bin/env ruby
File.chmod 0644, "test.txt"


cp.rb
#!/usr/bin/env ruby

# Validations... validations... validations...
if ARGV.length 
delete-file.rb
#!/usr/bin/env ruby
if ARGV.length 
listdir.rb
d = Dir.new(ARGV[0])
d.each {|file| puts file }


recursive-copy.rb
#!/usr/bin/env ruby
require 'Fileutils'

if ARGV.length 
rename-file.rb
#!/usr/bin/env ruby
if ARGV.length 
scan-setuid-files.rb
#!/usr/bin/env ruby
Dir.open(ARGV[0]).each { |file| puts file if File.setuid? ARGV[0] + "/" + file }

Tags: