反斜线不是最后一个字符吗?

时间:2020-06-23 10:18:53

标签: ruby rake-task rakefile

我有一个瑞克任务:

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

通过它可以正常工作,还有其他好的方法吗

1 个答案:

答案 0 :(得分:1)

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

%(...)创建一个可在其中使用字符串插值的字符串。在此字符串中,您可以使用'",而不必逃避或使用怪异的技巧。您仍然可以在字符串中使用括号,但是必须始终有匹配的对。 (如果括号不匹配,则可以使用其他定界符,例如%|...|%{...}%!...!等)

%(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)};}};')
相关问题