我已经对一些Ruby脚本进行了调整,以完全满足您的需求。这是Ruby代码:
#!/usr/bin/ruby
# Inspired by http://vikhyat.net/code/snippets/#watchfile
# How to use:
# This script takes two paramaters:  a folder and a shell command
# The script watches for when files in the folder are changed.  When they are, the shell command executes
# Here are some shortcuts you can put in the shell script:
# %F = filename (with extension)
# %B = base filename (without extension)
unless ARGV.length == 2
  puts "\e[32m    Usage: \e[0mruby OnSaveFolder.rb 'folder' 'command'"
  exit
end
require 'digest/md5'
require 'ftools'
$md5 = ''
$directory = File.expand_path(ARGV[0])
$contents = `ls #{$directory}`
$contentsList = $contents.split("\n")
$fileList = []
Dir.chdir($directory)
for i in $contentsList
  if ( File.file?(File.expand_path(i)) == true)
    $fileList.push(i)
  end
end
$processes = []
def watch(file, timeout, &cb)
  $md5 = Digest::MD5.hexdigest(File.read(file))
  loop do
    sleep timeout
    if ( temp = Digest::MD5.hexdigest(File.read(file)) ) != $md5
      $md5 = temp
      cb.call(file)
    end
  end
end
puts "\e[31m Watching files in folder \e[34m #{$directory}"
puts "\e[32m    Press Control+C to stop \e[0m"
for i in $fileList
  pid = fork do
    $num = 0
    $filePath = File.expand_path(i)
    watch i, 1 do |file|
      puts "\n     #{i} saved"
      $command = ARGV[1].dup
      if ( ARGV[1].include?('%F') )
        $command = $command.gsub!('%F', i)
      end
      if ( ARGV[1].include?('%B') )
        $command = $command.gsub!('%B', File.basename(i, '.*'))
      end
      $output = `#{$command}`
      if ( $output != '')
        puts "\e[34m     #{$command}\e[31m output: \e[0m"
        puts $output
      end
      puts "\e[34m     #{$command}\e[31m finished \e[0m (#{$num}, #{Time.now})\n"
      $num += 1
    end
  end
  $processes.push(pid)
end
Process.wait(pid)
for i in $processes
  `kill #{i}`
end
我将此脚本命名为“ OnSaveFolder.rb”。它有两个参数:要监视更改的文件夹,以及发生更改后要运行的bash代码。例如,
ruby OnSaveFolder.rb '/home/Movies' 'echo "A movie has been changed!"'
我希望这有帮助!我发现ruby对于这种类型的东西非常有效,并且默认情况下已安装在OS X上。
               
              
fswatchOS X的,我对被标记为重复问题发现- superuser.com/questions/445907/...