Shell time operation and calculation method _linux Shell

Source: Internet
Author: User

In recent time, when dealing with shell scripts, encountered time processing problems. The addition and subtraction of time, as well as the calculation of timing.

I. Time Plus and minus

The way to do this is to turn the base time into a timestamp, and then you need to add or change time to seconds.

For example: 1990-01-01 01:01:01 plus 1 hours 20 minutes

Processing method:

A. Converting the base time to time stamp

time1=$ (Date +%s-d ' 1990-01-01 01:01:01 ')

echo $time 1

631126861 "timestamp"

B. Increase the time into seconds

[Root@localhost ~]# time2=$ ((1*60*60+20*60))
[Root@localhost ~]# echo $time 2

4800

C. Two time added to calculate the result time

time1=$ (($time 1+ $time 2))

time1=$ (date +%y-%m-%d\%h:%m:%s-d "1970-01-01 UTC $time 1 Seconds");

echo $time 1

1990-01-01 02:21:01

Second, the calculation method of time difference

such as: 2010-01-01 and 2009-01-01 11:11:11 time lag

Principle: Also turn into a timestamp, and then calculate the day, time, minutes, seconds

Time1=$ (($ (Date +%s-d ' 2010-01-01 ')-$ (Date +%s-d ' 2009-01-01 11:11:11 '));

Echo time1


Will time1/60 seconds, will become divided.


Supplementary Note:

Shell single bracket operator symbol:

Copy Code code as follows:

a=$ (date);

Equivalent to: a= ' Date ';

Double bracket Operator:

Copy Code code as follows:

a=$ ((1+2));

echo $a;


Equivalent to:
Copy Code code as follows:

A= ' expr 1 + 2 '

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.