Your ps -cl1
output is as follows:
UID PID PPID F CPU PRI NI SZ RSS WCHAN S ADDR TTY TIME CMD 501 185 172 104 0 31 0 2453272 1728 - S ffffff80145c5ec0 ?? 0:00.00 httpd 501 303 1 80004004 0 31 0 2456440 1656 - Ss ffffff8015131300 ?? 0:11.78 launchd 501 307 303 4004 0 33 0 2453456 7640 - S ffffff8015130a80 ?? 0:46.17 distnoted 501 323 303 40004004 0 33 0 2480640 9156 - S ffffff80145c4dc0 ?? 0:03.29 UserEventAgent
So the last entry on each line is your team. This means that you can use the full power of regular expressions to help you.
$
in the regular expression means the end of the line, so you can use $
to indicate that not only the output should have Skype
in it, it should end in Skype
. This means that if you have a command called Skype Controller
, you wonโt pull it:
ps -clx | grep 'Skype$' | awk '{print $2}' | head -1
You can also simplify things by using the ps -o
format to just pull up the columns you need:
ps -eo pid,comm | grep 'Skype$' | awk '{print $1}' | head -1
And you can eliminate the head
simply by using awk
ability to choose your line for you. In awk
, NR
is your entry number. So you can do this:
ps -eo pid,comm | grep 'Skype$' | awk 'NR == 1 {print $1}'
Damn, now that I think about it, we could also eliminate grep
:
ps -eo pid,comm | awk '/Skype$/ {print $1; exit}'
This is using awk to use regular expressions. If the line contains a regular expression, "Skype $", it will print the first column, and then exit
The only problem is that if you had the Foo Skype
team, it would also pick it up. To fix this, you need to do a bit more bizarre work:
ps -eo pid,comm | while read pid command do if [[ "$command" = "Skype" ]] then echo $pid break fi done
while read
reads two variables. The trick is that read
uses a space to separate the variables it reads. However, since there are only two variables, the latter will contain the rest of the entire string. Thus, if the command is a Skype controller, the entire command will be placed in $command
, although there is a space in it.
Now we do not need to use a regular expression. We can compare the team with equality.
It is longer to enter, but in reality you use fewer commands and fewer connections. Remember that awk
loops through each line. Everything you do here makes it more explicit. In the end, it is actually much more effective than what you originally had.