Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add seconds to current time in Bash [duplicate]

Tags:

date

bash

time

I want to add 10 seconds 10 times. But I don't know well how to add times to the value.

This is my code.

./time.sh

time=$(date)
counter=1
while [ $counter -le 10 ] 
do
    echo "$time"
    time=$('$time + 10 seconds') //error occurred.
    ((counter++))
done

echo All done
like image 967
YEEN Avatar asked Sep 01 '25 21:09

YEEN


1 Answers

Using GNU Date

Assuming GNU date, replace:

time=$('$time + 10 seconds')

with:

time=$(date -d "$time + 10 seconds")

Putting it all together, try:

$ cat a.sh
t=$(date)
counter=1
while [ "$counter" -le 10 ]
do
    echo "$t"
    t=$(date -d "$t + 10 seconds")
    ((counter++))
done

echo All done

(I renamed time to t because time is also a bash built-in command and it is best to avoid potential confusion.)

When run, the output looks like:

$ bash a.sh
Tue Jan 16 19:19:44 PST 2018
Tue Jan 16 19:19:54 PST 2018
Tue Jan 16 19:20:04 PST 2018
Tue Jan 16 19:20:14 PST 2018
Tue Jan 16 19:20:24 PST 2018
Tue Jan 16 19:20:34 PST 2018
Tue Jan 16 19:20:44 PST 2018
Tue Jan 16 19:20:54 PST 2018
Tue Jan 16 19:21:04 PST 2018
Tue Jan 16 19:21:14 PST 2018
All done

Using Bash (>4.2)

Recent versions of bash support date calculations without external utilities. Try:

$ cat b.sh
#!/bin/bash
printf -v t '%(%s)T' -1
counter=1
while [ "$counter" -le 10 ]
do
    ((t=t+10))
    printf '%(%c)T\n' "$t"
    ((counter++))
done

echo All done

Here, t is time since epoch in seconds.

When run, the output looks like:

$ bash b.sh
Tue 16 Jan 2018 07:31:44 PM PST
Tue 16 Jan 2018 07:31:54 PM PST
Tue 16 Jan 2018 07:32:04 PM PST
Tue 16 Jan 2018 07:32:14 PM PST
Tue 16 Jan 2018 07:32:24 PM PST
Tue 16 Jan 2018 07:32:34 PM PST
Tue 16 Jan 2018 07:32:44 PM PST
Tue 16 Jan 2018 07:32:54 PM PST
Tue 16 Jan 2018 07:33:04 PM PST
Tue 16 Jan 2018 07:33:14 PM PST
All done
like image 86
John1024 Avatar answered Sep 03 '25 13:09

John1024