backslash not last charcter on line?

122 Views Asked by At

I have a rake task:

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

I am getting :

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

Any solution to resolve this?

I tried out this :

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

With this it is working fine, is there any other good way to do it

1

There are 1 best solutions below

0
3limin4t0r On

Your current solution is fine, but could be improved. Instead of using + to concatenate the strings, you could use string interpolation with #{...} instead in combination with %(...).

The %(...) creates a string in which string interpolation can be used. In this string you can use ' and " without escaping or weird tricks. You can still use parentheses in the string, but there must always be matching pairs. (If you have unmatched parentheses you can use another delimiter eg. %|...|, %{...}, %!...! etc.)

%(foo bar)
#=> "foo bar"
%("foo" ('bar'))
#=> "\"foo\" ('bar')"
%("foo" ('#{1 + 1}'))
#=> "\"foo\" ('2')"

Applying this to your command it would look like this:

ruby_process_command = %(ps -ef | awk '{if( $8~"ruby"&& $2!=#{current_process_id}){printf("Killing ruby process: %s \\n",$2);{system("kill -9 "$2)};}};')