How do I use Ruby for shell scripting?

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

    By default, you already have access to Dir and File, which are pretty useful by themselves.

    Dir['*.rb'] #basic globs
    Dir['**/*.rb'] #** == any depth of directory, including current dir.
    #=> array of relative names
    
    File.expand_path('~/file.txt') #=> "/User/mat/file.txt"
    File.dirname('dir/file.txt') #=> 'dir'
    File.basename('dir/file.txt') #=> 'file.txt'
    File.join('a', 'bunch', 'of', 'strings') #=> 'a/bunch/of/strings'
    
    __FILE__ #=> the name of the current file
    

    Also useful from the stdlib is FileUtils

    require 'fileutils' #I know, no underscore is not ruby-like
    include FileUtils
    # Gives you access (without prepending by 'FileUtils.') to
    cd(dir, options)
    cd(dir, options) {|dir| .... }
    pwd()
    mkdir(dir, options)
    mkdir(list, options)
    mkdir_p(dir, options)
    mkdir_p(list, options)
    rmdir(dir, options)
    rmdir(list, options)
    ln(old, new, options)
    ln(list, destdir, options)
    ln_s(old, new, options)
    ln_s(list, destdir, options)
    ln_sf(src, dest, options)
    cp(src, dest, options)
    cp(list, dir, options)
    cp_r(src, dest, options)
    cp_r(list, dir, options)
    mv(src, dest, options)
    mv(list, dir, options)
    rm(list, options)
    rm_r(list, options)
    rm_rf(list, options)
    install(src, dest, mode = , options)
    chmod(mode, list, options)
    chmod_R(mode, list, options)
    chown(user, group, list, options)
    chown_R(user, group, list, options)
    touch(list, options)
    

    Which is pretty nice

提交回复
热议问题