Turn null value into 0 with a Bash Script

Hi,

I'm trying to make a bash script that if a null value is returned then to output the value 0.

I would like a script to search the 'top' tree and return the CPU value of a process, however if the process is not running for it to return 0 or another identifier.

top -b -n1 | awk '/ PROCESS /{print $9}'

Any help appreciated.

Try this:

top -b -n1 | awk '/ PROCESS /{CPU+=$9} END { printf "%03.1f\n",CPU }'

Perfect thank you.

I'm not sure how, but it worked.

Many thanks.

I'll try and explain CPU+=$9 is equivalent to CPU=CPU+$9 , so you can see we are adding up all the CPU for all lines that match your process.

END { printf "%03.1f\n", CPU } when the end of input is reached the total CPU is printed, the format of printf is a little tricky (man printf may be of help here).
In this case we are forcing 1 decimal place and require a leading zero if value is less than 1 (eg 0.5).

Thanks for your explanation. That makes sense. I have not used printf before, seems like it come in handy.

Cheers, for all your help.