【问题标题】:backslash not last charcter on line?反斜杠不是在线的最后一个字符?
【发布时间】:2020-10-13 09:06:14
【问题描述】:

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

这样就可以正常使用了,有没有其他的好方法呢

【问题讨论】:

    标签: ruby rake-task rakefile


    【解决方案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)};}};')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-12-07
      • 1970-01-01
      • 2015-07-29
      • 2014-12-04
      • 2017-10-10
      • 2016-03-18
      • 1970-01-01
      相关资源
      最近更新 更多