For troubleshooting purpose, I'd like to record PID and its command every 15s and write them to a text file.

The desired output: TimeStamp, PID, Command


This will get you you the three columns you want:

$ ps -hopid,comm | perl -anle'print time, ", $F[0], $F[1]"'
1541626566, 6496, gedit
1541626566, 7513, bash

You can limit or extend the scope of ps, ie. what processes it lists. Then you put this in a loop with redirection.

while true; do echo x; sleep 15; done > out

Replace echo x with the command proper and out with the file name you choose.

As for the command producing the information, here's a run-down.

  • ps -hopid,comm - ps is obvious, -h turns off the header line and -o stands for the output (PID and command).
  • This goes to the Perl command, namely perl -anle'print time, ", $F[0], $F[1]"'. Here perl is Perl. The -anle flags reprent correspondingly: a - load input into an array, n - take care of new lines, l - process each single line, and finally e - execute the code that follows.
  • And now the code follows: 'print time, ", $F[0], $F[1]"'. First print the time stamp, then the first column of the array that holds the input material, and then the second.
| improve this answer | |

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.