Code:
top | awk '
/^CPU states:/ {
sub(/%/,"",$3);
if ($3 == 0)
exit 1;
else
exit 0}
' || ps -ef > output_file
top | awk ... || ps
The output of the 'top' command is processed by 'awk'.
If the status of awk is not succes (!= 0) the "ps' command is executed.
The 'awk' script exit with status 1 when CPU state is zero.
/^CPU states:/
Select record from 'top' output stating with 'CPU states:'. In the output example you gived, the selected record is :
CPU states: 56.1% idle, 20.4% user, 19.7% kernel, 3.9% iowait, 0.0% swap
The CPU state 56.1% is field 3.
sub(/%/,"",$3)
Substitute the '%' character by nothing in field 3. Field 3 bocomes '56.1'
The same thing can be done by 'substr($3,1,length($3)-1)' since '%' is the last character of the string.
if ($3 == 0) exit 1;
If the CPU state is equal to zero, exit from awk with status 1.
When the status of awk is not succes (!= 0), the 'ps -ef' command will be executed because it is preceded by the || operator
else exit 0
The CPU state is non zero, exit awk with status 0.
The 'ps -ef' command will not be executes