7

how to print ps header when using pipe in linux

this normal ps output

$ ps -ef
UID         PID   PPID  C STIME TTY          TIME CMD
root          1      0  0 17:00 ?        00:00:02 /usr/lib/systemd/systemd

but below ps command output without header

$ ps -ef | grep systemd
root          1      0  0 17:00 ?        00:00:02 /usr/lib/systemd/systemd

how do i print ps header for second command?

thx

public_name
  • 71
  • 2
  • 2
  • 4

2 Answers2

5

My first instinct is to do ps -ef | grep UID && ps -ef | grep systemd, but that will also print the grep commands like so

$ ps -ef | grep UID && ps -ef | grep systemd
UID         PID   PPID  C STIME TTY          TIME CMD
root          1      0  0 17:00 ?        00:00:02 /usr/lib/systemd/systemd
user          PID PPID  C 23:30 ?        00:00:00 grep systemd
user          PID PPID  C 23:30 ?        00:00:00 grep UID

I don't see how you can print only the header, because any time you execute this, the regex will match the grep itself.

1

This works to avoid having the greps in there

ps -ef > tmpfile.txt; egrep 'UID|systemd' tmpfile.txt; rm tmpfile.txt