How do I use Ruby for shell scripting?

前端 未结 13 1856
粉色の甜心
粉色の甜心 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:22

    Here's something important that's missing from the other answers: the command-line parameters are exposed to your Ruby shell script through the ARGV (global) array.

    So, if you had a script called my_shell_script:

    #!/usr/bin/env ruby
    puts "I was passed: "
    ARGV.each do |value|
      puts value
    end
    

    ...make it executable (as others have mentioned):

    chmod u+x my_shell_script
    

    And call it like so:

    > ./my_shell_script one two three four five
    

    You'd get this:

    I was passed: 
    one
    two
    three
    four
    five
    

    The arguments work nicely with filename expansion:

    ./my_shell_script *
    
    I was passed: 
    a_file_in_the_current_directory
    another_file    
    my_shell_script
    the_last_file
    

    Most of this only works on UNIX (Linux, Mac OS X), but you can do similar (though less convenient) things in Windows.

    0 讨论(0)
提交回复
热议问题