If $2 is null

Hello,
I am running Ubuntu 18.04.
How may I set a rule like "if $2 is null, skip this line" :

rm restart
..
..
..
echo "kill -9 `ps aux | grep -v grep | grep hts | awk '{ print $2 }'`" >> restart

restart :

kill -9
kill -9 15549
kill -9 21845

The first line is the problem.
Expected output:

kill -9 15549
kill -9 21845

Related thread:
https://community.unix.com/t/mem-ps-v-ppid-grep-i-db2-grep-v-grep-awk-if-7-print-0-else/212979/3
Thank you
Boris

show example output going into the awk command please

use number of fields in the stream ...

'NF >2 {....'
'NF == 3 {...'

look at using pgrep rather than ps/grep
look at using "$(commands)" rather than backtick commands

run your script through shellcheck (install it if not already installed) - its also available online and follow its advice.

2 Likes

With pgrep and shell builtins

pids=$(pgrep -f hts); [ "$pids" ] && echo kill -9 $pids >> restart

Regarding shellcheck, the $pids must be unquoted to achieve word-splitting - each word is a pid.

A warning:
hts is very short, can easily be part of other process names...
At least consider word boundaries "\<hts\>" (works with grep and pgrep; grep also has got a -w option).
Also in pgrep you can specify a user e.g.
pgrep -f -u root "\<hts\>"

1 Like

Thank you @MadeInGermany @munkeHoller
MadeInGermany's code did pan out as expected..

Much appreciated
Thank you
Boris

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.