ruby - 反斜杠不是在线的最后一个字符?
问题描述
我有一个 rake 任务:
task :kill_process do
current_process_id = Process.pid
puts current_process_id
ruby_process_command = "ps -ef | awk '{if( $8~" + "ruby && $2!=" + current_process_id.to_s + "){printf(" + "Killing ruby process: %s " + "\\n " + ",$2);{system(" + "kill -9 " + "$2)};}};'"
puts ruby_process_command
system (ruby_process_command)
end
我正进入(状态 :
awk: cmd. line:1: {if( $8~ruby && $2!=23699){printf(Killing ruby process: %s \n ,$2);{system(kill -9 $2)};}};
awk: cmd. line:1: ^ syntax error
awk: cmd. line:1: {if( $8~ruby && $2!=23699){printf(Killing ruby process: %s \n ,$2);{system(kill -9 $2)};}};
awk: cmd. line:1: ^ backslash not last character on line
有什么解决方案可以解决这个问题?
我试过这个:
ruby_process_command = "ps -ef | awk '{if( $8~" + '"' + "ruby" + '"' + "&& $2!=" + current_process_id.to_s + "){printf(" + '"' + "Killing ruby process: %s " + "\\n" + '"' + ",$2);{system(" + '"' + "kill -9 " + '"' + "$2)};}};'"
有了它,它工作正常,有没有其他好的方法可以做到这一点
解决方案
您当前的解决方案很好,但可以改进。您可以使用字符串插值而不是使用+
来连接字符串,#{...}
而不是结合使用%(...)
.
%(...)
创建一个可以使用字符串插值的字符串。在这个字符串中,您可以使用'
并且"
没有转义或奇怪的技巧。您仍然可以在字符串中使用括号,但必须始终存在匹配对。(如果您有不匹配的括号,您可以使用另一个分隔符,例如,%|...|
等)%{...}
%!...!
%(foo bar)
#=> "foo bar"
%("foo" ('bar'))
#=> "\"foo\" ('bar')"
%("foo" ('#{1 + 1}'))
#=> "\"foo\" ('2')"
将此应用于您的命令,它看起来像这样:
ruby_process_command = %(ps -ef | awk '{if( $8~"ruby"&& $2!=#{current_process_id}){printf("Killing ruby process: %s \\n",$2);{system("kill -9 "$2)};}};')
推荐阅读
- mongodb - 将 MongoDB 查询转换为 Scala
- algorithm - 二次探测:在现实生活中的哪种情况下会是 O(n) 复杂度
- c++ - 从 sockaddr_in* 到 sockaddr* 的类型转换是否违反了“严格的别名规则”?
- react-native - 找不到包含 /file:/data/user/0/react-native-mail 的已配置根目录
- python - 如何访问从另一个文件打开的硒驱动程序?
- discord.js - 无法使用 member.roles.add (id) 分配角色
- postgresql - 无法将 pgAdmin4 与 ElephantSQL 连接
- ruby-on-rails - Devis 注销错误 ActionController::InvalidAuthenticityTokenon 注销
- python - 在 apache 上运行烧瓶
- visual-studio-code - 保存在 vscode 中时自动应用更改