I’m using awk to get the pid of a specific process by name.
#!/bin/sh
for pid in $(ps | awk '$4 == "foo" { print $1 }')
do
i=1
echo "killing foo at pid $pid"
kill $pid && echo 'ok' || echo 'failed'
done
where ps output on OSX is something like:
$ ps
PID TTY TIME CMD
1858 ttys000 0:00.15 -bash
4148 ttys000 0:01.37 /a/b/c/foo
but my shell script only works if the process in the CMD column is exactly foo (no absolute paths).
I’m thinking I can use basename, but how do I call it from awk?
OR
Is there something like $4.endswith('foo') in awk?
awkcan use regular expressions. So rather than$4 == "foo", you could do something like:The regular expression is between the
/and/.\/foo$says “a backslash followed by foo and then the end of the field.” In this case, your field is/a/b/c/foo, so it would match.