如何使用 Ruby 编写 shell 脚本? [英] How do I use Ruby for shell scripting?

查看:32
本文介绍了如何使用 Ruby 编写 shell 脚本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些简单的 shell 脚本任务要完成

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 expression.

我知道我可以使用标准的 bash 和 grep 来做这种事情,但我很高兴能够破解可以在 windows 和 linux 中运行的快速脚本,而我不必记住一堆命令行程序和标志等

I know that I can do this sort of thing using standard bash and grep but I would be nice to be able to hack quick scripts that will work in windows and linux without me having to memorize a heap of command line programs and flags etc.

我试图让这个进行,但最终对我应该从哪里获取信息(例如对当前目录的引用)感到困惑

I tried to get this going but ended up getting confused about where I should be getting information such as a reference to the current directory

那么问题是我需要知道 Ruby 库的哪些部分才能编写 ruby​​ shell 脚本?

So the question is what parts of the Ruby libraries do I need to know to write ruby shell scripts?

推荐答案

默认情况下,您已经可以访问 Dir文件,其中本身就很有用.

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

来自 stdlib 的还有 FileUtils

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 = <src's>, options)
chmod(mode, list, options)
chmod_R(mode, list, options)
chown(user, group, list, options)
chown_R(user, group, list, options)
touch(list, options)

哪个好看

这篇关于如何使用 Ruby 编写 shell 脚本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆