这在Ruby中正常工作,它应该工作:
puts 'don\'t'
但我想在使用Ruby运行BASH相同:
%x(echo 'don\'t')
我得到这个错误:sh: -c: line 0: unexpected EOF while looking for matching
''`
与``,system()
,Open3
发生同样的错误
我实际的代码片段:
require 'open3'
module XdoTool
BIN = 'xdotool'
EXEC = ::ENV['PATH'].split(::File::PATH_SEPARATOR).map { |path| ::File.join(path, BIN) if ::File.executable?(::File.join(path, BIN)) }.compact.last
raise RuntimeError, "No #{BIN} found in the exported paths. Please make sure you have #{BIN} installed" unless EXEC
class << self
def type(str)
Open3.capture2("#{EXEC} type --delay 0 '#{str = str.gsub("'", '\'')}'")
str
end
end
end
# Types the quoted text anywhere.
XdoTool.type("What is the reason of the error?")
# sh: -c: line 0: unexpected EOF while looking for matching `''
# sh: -c: line 1: syntax error: unexpected end of file
XdoTool.type("What's the reason of the error?")
请注意,STR可以有什么。它可以包含字母数字字符,符号,表情符号,或组合的所有这些事情。我怎样才能解决与此报价的问题?
在外壳,你根本不能包含一个单引号的字符串内使用单引号。它必须是在双引号的字符串。这意味着,如果你想同时包含一个参数,你需要连接另议刺在一起。
echo 'He said "I can'"'"t'"'
或逃避双引号字符串中的双引号
echo "He said \"I can't\""
(有些shell提供报价,可以包含一个转义单引号,即$'He said "I can\'t"'
的另一种形式。但是,这是一个扩展,你不能假设由外壳红宝石将用来执行你的命令支持POSIX标准。)