首页 > 解决方案 > 反斜杠不是在线的最后一个字符?

问题描述

我有一个 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)};}};'"

有了它,它工作正常,有没有其他好的方法可以做到这一点

标签: rubyrake-taskrakefile

解决方案


您当前的解决方案很好,但可以改进。您可以使用字符串插值而不是使用+来连接字符串,#{...}而不是结合使用%(...).

%(...)创建一个可以使用字符串插值的字符串。在这个字符串中,您可以使用'并且"没有转义或奇怪的技巧。您仍然可以在字符串中使用括号,但必须始终存在匹配对。(如果您有不匹配的括号,您可以使用另一个分隔符,例如,%|...|等)%{...}%!...!

%(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)};}};')

推荐阅读