user3345547
user3345547

Reputation: 725

operation on variable with date generate error

How I can minus 30 minutes from variable?

#!/bin/bash

date_30=$(date --date '-30 min')
date_60=$($date_30 --date '-30 min')
    
exit 0

but I get

./a.sh: 4: ./a.sh: Thu: not found

Upvotes: 0

Views: 149

Answers (1)

Léa Gris
Léa Gris

Reputation: 19555

date_30=$(date --date '-30 min')

This is storing the output of date --date '-30 min' into the date_30 variable, which is something like: Thu Aug 13 13:09:04 CEST 2020

date_60=$($date_30 --date '-30 min')

Executes the content of the $date_30 variable with word splitting on space (since it has no enclosing double quotes "), so it tries to execute Thu with the parameters Aug, 13, 13:09:04, CEST, 2020, --date and -30 min and surely there is no command named Aug and this is surely not what you try to do.

To fix it:

date_60=$(date --date "$date_30 -30 min")

Or use Shell arithmetic with timestamp dates:

# Store date 30 as timestamp
date_30=$(date +%s)

# Bash arithmetically subtract 1800 seconds (30 min)
date_60=$((date_30-1800))

# Print first date from timestamp into human readable
date --date "@$date_30"

# Print second date from timestamp into human readable
date --date "@$date_60"

Upvotes: 1

Related Questions