For the script I've written to show only last n hour of log messages, you will notice that it only works correctly if user is sensible enough to enter a number in the range that is within the current hour of time.

If a user enters a number e.g."25", which exceeds the current hour e.g. 13:00,

If a user enters a number e.g."25", which exceeds the current hour e.g. 13:00,

The script output will start from13:00 hour which doesn't seem right.

We want any input of number larger than or equal to the current hour to be starting from 00:00 hour which is more logical. Example 2 below will solve the problem.

We want any input of number larger than or equal to the current hour to be starting from 00:00 hour which is more logical. Example 2 below will solve the problem.

**Example 1**

...

to_day=`date +"%d"`

cur_hour=`date +"%H"`

date_month=`date +"%Y%m"

to_day=`date +"%d"`

cur_hour=`date +"%H"`

date_month=`date +"%Y%m"

last_x_hour=${2:-1}

last_n_hour=`[[ last_x_hour -gt $cur_hour ]] && echo "0" || echo "$last_x_hour"`

from_hr=`expr $cur_hour - $last_n_hour `

last_n_hour=`[[ last_x_hour -gt $cur_hour ]] && echo "0" || echo "$last_x_hour"`

from_hr=`expr $cur_hour - $last_n_hour `

....

....

Replace the above with below will solve the problem

**Example 2**

to_day=`date +"%d"`

hour_now=`date +"%H"` # hour_now in 24 hour format

cur_hour=${hour_now#0}

#cur_hour will have leading "0" e.g "09" if $hour_now is less 10, and it cannot be used to compare numerically. so the leading "0" has to be removed using parameter substitution as above.

date_month=`date +"%Y%m"

hour_now=`date +"%H"` # hour_now in 24 hour format

cur_hour=${hour_now#0}

#cur_hour will have leading "0" e.g "09" if $hour_now is less 10, and it cannot be used to compare numerically. so the leading "0" has to be removed using parameter substitution as above.

date_month=`date +"%Y%m"

last_n_hour=${last_x_hour#0} # remove leading "0" if user enter something like "09"

diff_last_hour=$(( $cur_hour - $last_n_hour )) #alternative of calculating values using $ (( a + b )) instead of using "expr"

from_hr=0

[[ $last_x_hour -ge $cur_hour ]] && from_hr=0 || from_hr=$diff_last_hour

from_hr=0

[[ $last_x_hour -ge $cur_hour ]] && from_hr=0 || from_hr=$diff_last_hour

...

end

## Comments (0)

There are no comments to displayAdd a Comment