简体   繁体   中英

How to use time in shell script?

I have small shell script where I'm checking time I got same time whereas I'm using sleep for 10 sec.

#!/bin/bash

date=`date +%H:%m:%S`
echo $date
sleep 10
echo $date

output:

07:10:48

07:10:48

output should be like this

07:10:48

07:10:58

You are printing the same variable ( date )twice. Here is the fix:

#!/bin/bash

date=`date +%H:%m:%S`
echo $date
sleep 10
date=`date +%H:%m:%S`
echo $date

And you'll get what you expected!

DRY: use a function

mydate() { date +%T; }

mydate
sleep 10
mydate

Or, use it like a variable:

echo "current time is $(mydate)"

btw, %m is the month (10), %M is the minute.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM