1

I have the following command:

ps -ef | awk '{if( $8~"java" || $8~"ruby" || $8~"god"){printf("Killing : %s \n",$2);{system("kill -9 "$2)};}};'

How do i excute this linux command from rakeFile.

I tried:

task :kill_process do
  `ps -ef | awk '{if( $8~"java" || $8~"ruby" || $8~"god"){printf("Killing : %s \n",$2);{system("kill -9 "$2)};}};'`
end

But on executing it's giving error:

awk: cmd. line:1: {if( $8~"java" || $8~"glassfish" || $8~"ruby" || $8~"god" || $8~"couch"){printf("Killing : %s 
awk: cmd. line:1:                                                                                 ^ unterminated string
awk: cmd. line:1: {if( $8~"java" || $8~"glassfish" || $8~"ruby" || $8~"god" || $8~"couch"){printf("Killing : %s 
awk: cmd. line:1:                                                                                 ^ syntax error

I got the solution for my problem: Thanks to @Yurii Verbytskyi

task :kill_process do
   system %q(ps -ef | awk '{if( $8~"java" || $8~"ruby" || $8~"god"){printf("Killing : %s \n",$2);{system("kill -9 "$2)};}}') 
end

Nitin Singhal
  • 215
  • 2
  • 11
  • Does this command run directly on the command line? It appears to contain some ruby method calls. – AJFaraday Jun 19 '20 at 06:45
  • This works fine directly on command line. – Nitin Singhal Jun 19 '20 at 06:48
  • 1
    you can try https://ruby-doc.org/core-2.7.1/Kernel.html#method-i-system task :kill_process do system %q(ps -ef | awk '{if( $8~"java" || $8~"ruby" || $8~"god"){printf("Killing : %s \n",$2);}}') end * I removed kill command to test it locally) – Yurii Verbytskyi Jun 19 '20 at 07:01
  • @YuriiVerbytskyi thanks, it is working. Can u please tell me what is %q here – Nitin Singhal Jun 19 '20 at 07:06
  • https://simpleror.wordpress.com/2009/03/15/q-q-w-w-x-r-s/ this is alternative single quotes syntax. Just used it because of different quotes are present in your command string – Yurii Verbytskyi Jun 19 '20 at 07:09
  • Does this answer your question? [Execute bash commands from a Rakefile](https://stackoverflow.com/questions/9796028/execute-bash-commands-from-a-rakefile) – Mosaaleb Jun 19 '20 at 09:09

1 Answers1

2

Try this one.

task :kill_process do
   system("ps -ef | awk '{if( $8~\"java\" || $8~\"ruby\" || $8~\"god\"){printf(\"Killing : %s \\n\",$2);{system(\"kill -9 \"$2)};}};'")
end

We need to escape special chars like \n

lokanadham100
  • 1,149
  • 1
  • 11
  • 22
  • What if i don't want the returned value of system method. Is there any way, not to get the returned value? – Nitin Singhal Jun 23 '20 at 07:05
  • Here you can use your code as well. But the problem with ur code is escaping special characters. If you do that ur code also works fine. – lokanadham100 Jun 28 '20 at 07:12