How do I use Ruby for shell scripting?

前端 未结 13 1964
粉色の甜心
粉色の甜心 2020-12-22 15:26

I have some simple shell scripting tasks that I want to do

For example: Selecting a file in the working directory from a list of the files matching some regular e

13条回答
  •  -上瘾入骨i
    2020-12-22 16:07

    The above answer are interesting and very helpful when using Ruby as shell script. For me, I does not use Ruby as my daily language and I prefer to use ruby as flow control only and still use bash to do the tasks.

    Some helper function can be used for testing execution result

    #!/usr/bin/env ruby
    module ShellHelper
      def test(command)
        `#{command} 2> /dev/null`
        $?.success?
      end
    
      def execute(command, raise_on_error = true)
        result = `#{command}`
        raise "execute command failed\n" if (not $?.success?) and raise_on_error
        return $?.success?
      end
    
      def print_exit(message)
        print "#{message}\n"
        exit
      end
    
      module_function :execute, :print_exit, :test
    end
    

    With helper, the ruby script could be bash alike:

    #!/usr/bin/env ruby
    require './shell_helper'
    include ShellHelper
    
    print_exit "config already exists" if test "ls config"
    
    things.each do |thing|
      next if not test "ls #{thing}/config"
      execute "cp -fr #{thing}/config_template config/#{thing}"
    end
    

提交回复
热议问题