How do I use Ruby for shell scripting?

前端 未结 13 1959
粉色の甜心
粉色の甜心 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条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-22 16:16

    As the others have said already, your first line should be

    #!/usr/bin/env ruby
    

    And you also have to make it executable: (in the shell)

    chmod +x test.rb
    

    Then follows the ruby code. If you open a file

    File.open("file", "r") do |io|
        # do something with io
    end
    

    the file is opened in the current directory you'd get with pwd in the shell.

    The path to your script is also simple to get. With $0 you get the first argument of the shell, which is the relative path to your script. The absolute path can be determined like that:

    #!/usr/bin/env ruby
    require 'pathname'
    p Pathname.new($0).realpath()
    

    For file system operations I almost always use Pathname. This is a wrapper for many of the other file system related classes. Also useful: Dir, File...

提交回复
热议问题