0

I am trying to manipulate timestamps using date in shell script. My code is this

echo $(date -d '+10 mins' +%s%N)

This will print time 10 mins from current time in nanoseconds

1554242194228787268

When i move the echo statement inside a for loop to do a custom action based on the loop variable.

for repi in `seq 1 2`;
do
    lp_incr=$((repi*10))
    n_incr='+'$lp_incr' mins'
    echo $(date -d $n_incr +%s%N)
done

Getting error like this

date: extra operand '+%s%N'

Remove that extra operand won't help me to view date alone

for repi in `seq 1 2`;
do
    lp_incr=$((repi*10))
    n_incr='+'$lp_incr' mins'
    echo $n_incr
    echo $(date -d $n_incr)
done

Again getting different error

+10 mins date: the argument 'mins' lacks a leading '+';

$n_incr have the '+'still it throws an error.

It seems like i miss something in this. Entire motive is generate timestamp in nano seconds for some interval. Thanks in advance for all suggestions or alternate approaches.

Rajan
  • 416
  • 1
  • 7
  • 25
  • See: [When to wrap quotes around a shell variable?](https://stackoverflow.com/questions/10067266/when-to-wrap-quotes-around-a-shell-variable) Short answer: almost always. – Gordon Davisson Apr 02 '19 at 22:16

1 Answers1

1

In

echo $(date -d $n_incr +%s%N)

$n_incr is expanded to

echo $(date -d +10 mins +%s%N)

Note that +10 mins is not a single argument, but two.

The fix is to quote the argument:

echo $(date -d "$n_incr" +%s%N)

You can also omit $n_incr:

echo $(date -d "+$lp_incr mins" +%s%N)
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143