I am trying to automate Forever JS to keep my dev server running and for that I need to check and stop the forever process to start another one. By running

sudo forever list

I get the following output:

info:    Forever processes running
data:        uid  command         script forever pid   id logfile                        uptime       
data:    [0] 0NQH /usr/bin/nodejs app.js 17047   17049    /home/ubuntu/.forever/0NQH.log 0:2:4:58.594

From the above output I need the pid which is 17049 currently and feed it to the next command like so:

sudo forever stop {{pidfromabove}}

To accomplish this, in my script I've tried out many things, mainly trying to find the two strings between app.js and /home but for some reason it keeps printing the whole line. I've tried different combinations of sed and awk. How do I get the pid from the above to feed to the next stop command?


2 Answers 2


This looks like a use case for awk. If you're sure that the output format is stable so that the PID you're interested in is always the 7th element of the line, this will print the PID for app.js:

sudo forever list | awk '/app\.js/ { print $7 }'

The issue you encounter may be because the output is on stderr, not on stdout. If this is the case, you can try:

sudo forever list 2>&1 | sed 's/.*app.js [0-9]* \([0-9]*\) /\1/'

It should answer just the second pid.

Then you could do:

sudo forever stop `sudo forever list 2>&1 | sed 's/.*app.js [0-9]* \([0-9]*\) /\1/'`
  • Sorry the first command instead of printing just the pid number prints the whole output like info: Forever processes running data: uid command script forever pid id logfile uptime 17049 /home/ubuntu/.forever/0NQH.log 0:2:24:45.113 Feb 22, 2016 at 10:10
  • My mistake, I didn't see that there were two lines ! You would need a grep in addition to the sed. The command is actually working on the data line (only 17049 printed) but not on the info line (fully printed) Feb 22, 2016 at 10:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.