當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Ruby Shellwords.shellescape用法及代碼示例

本文簡要介紹ruby語言中 Shellwords.shellescape 的用法。

用法

shellescape(str)
也別名為:escape

轉義字符串,以便可以在 Bourne shell 命令行中安全地使用它。 str 可以是響應 to_s 的非字符串對象。

請注意,結果字符串應該不帶引號使用,並且不打算在雙引號或單引號中使用。

argv = Shellwords.escape("It's better to give than to receive")
argv #=> "It\\'s\\ better\\ to\\ give\\ than\\ to\\ receive"

String#shellescape 是此函數的簡寫。

argv = "It's better to give than to receive".shellescape
argv #=> "It\\'s\\ better\\ to\\ give\\ than\\ to\\ receive"

# Search files in lib for method definitions
pattern = "^[ \t]*def "
open("| grep -Ern -e #{pattern.shellescape} lib") { |grep|
  grep.each_line { |line|
    file, lineno, matched_line = line.split(':', 3)
    # ...
  }
}

調用者有責任為使用該字符串的 shell 環境以正確的編碼對字符串進行編碼。

多字節字符被視為多字節字符,而不是字節。

如果 str 的長度為零,則返回空引用的 String

相關用法


注:本文由純淨天空篩選整理自ruby-lang.org大神的英文原創作品 Shellwords.shellescape。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。