module Shellwords

像 UNIX Bourne shell 一样操作字符串

此模块根据 UNIX Bourne shell 的词法分析规则操作字符串。

shellwords() 函数最初是 shellwords.pl 的移植,但为了符合 IEEE Std 1003.1-2008, 2016 Edition 的 Shell & Utilities 卷进行了修改。

用法

您可以使用 Shellwords 将字符串解析为 Bourne shell 友好的 Array

require 'shellwords'

argv = Shellwords.split('three blind "mice"')
argv #=> ["three", "blind", "mice"]

在 `require` 了 Shellwords 之后,您可以使用 `split` 别名 String#shellsplit

argv = "see how they run".shellsplit
argv #=> ["see", "how", "they", "run"]

它们将引号视为特殊字符,因此不匹配的引号将导致 ArgumentError

argv = "they all ran after the farmer's wife".shellsplit
     #=> ArgumentError: Unmatched quote: ...

Shellwords 还提供了相反的方法。 Shellwords.escape 或其别名 String#shellescape 会转义字符串中的 shell 元字符,以便在命令行中使用。

filename = "special's.txt"

system("cat -- #{filename.shellescape}")
# runs "cat -- special\\'s.txt"

请注意 `--`。没有它,`cat(1)` 会将后面的参数视为命令行选项,如果它以 `-` 开头。可以保证 Shellwords.escape 将字符串转换为 Bourne shell 能将其解析回原始字符串的形式,但程序员有责任确保将任意参数传递给命令不会造成损害。

Shellwords 还提供了对 Array 的核心扩展,即 Array#shelljoin

dir = "Funny GIFs"
argv = %W[ls -lta -- #{dir}]
system(argv.shelljoin + " | less")
# runs "ls -lta -- Funny\\ GIFs | less"

您可以使用此方法从参数数组构建一个完整的命令行。

作者

联系方式