BASH scripting question

Questions about applications and software
Forum rules
Before you post please read how to get help
Post Reply
User avatar
RedWagon
Level 5
Level 5
Posts: 632
Joined: Tue May 26, 2009 6:41 pm

BASH scripting question

Post by RedWagon » Mon Jul 05, 2010 10:33 am

I'm trying to format the output of uptime from

Code: Select all

 10:34:34 up 3 days,  1:02, load average: 0.00, 0.00, 0.00
to

Code: Select all

3 days,  1:02
by cutting everything before "up " and everything after ", load" in bash.

antonone
Level 1
Level 1
Posts: 20
Joined: Thu Mar 18, 2010 1:39 pm
Location: Poland
Contact:

Re: BASH scripting question

Post by antonone » Mon Jul 05, 2010 11:00 am

I've a different suggestion. `uptime` gives different output depending on the locale on a specified system. This can be problematic to parse sometimes (if you want to share this script over different installations of Linux). It's easier to depend on `/proc/uptime` contents.

The /proc/uptime file contains two values separated by a space - the first one is most important, as it's a number of seconds since boot time. You can read this value, perform some calculations on it to extract the day, hour, minute and second of the system uptime. I've included an example of how you may do it:

Code: Select all

time=`cat /proc/uptime | cut -d. -f1`

days=$((time/60/60/24))
hour=$((time/60/60))
minute=$((time/60%60))
second=$((time%60))

# if $days are [g]reater [t]han ("gt") zero, then:
if [ $days -gt 0 ]; then
    echo -n "$days days "
fi  

# write rest of data
printf "%02d:%02d:%02d\n" $hour $minute $second
This script will display a string like:

Code: Select all

$ ./bash-script.sh 
01:46:09
and that's the same value uptime will give:

Code: Select all

$ uptime
 17:04:32 up  1:46,  2 users,  load average: 0.01, 0.03, 0.00

User avatar
RedWagon
Level 5
Level 5
Posts: 632
Joined: Tue May 26, 2009 6:41 pm

Re: BASH scripting question

Post by RedWagon » Mon Jul 05, 2010 12:39 pm

Thanks antonone, that works great. There was a small mistake though, the hours line should look like this:

Code: Select all

hour=$((time/60/60%24))
otherwise it shows total hours and not just hours for that day.

antonone
Level 1
Level 1
Posts: 20
Joined: Thu Mar 18, 2010 1:39 pm
Location: Poland
Contact:

Re: BASH scripting question

Post by antonone » Mon Jul 05, 2010 1:24 pm

Of course you're right. Glad it helped ;).

Post Reply

Return to “Software & Applications”