Search code examples
linuxbashshelldate

How to calculate past or future date based on input date value in bash


I am trying to calculate the past date based on the input date value provided by a user to a bash script.

For instance if user provides input value as 20240224 (YYYYMMDD format) I want to calculate the date the which is 2 days ago. So, in this case the calculated date should be 20240222.

As per my understanding Linux/bash has below option to calculate it from the current date as below.

date -d "2 days ago" +%Y%m%d

How can I calculate, based on the user input value? Please advise.


Solution

  • Check this out:

    #!/bin/bash
    
    read -p 'Type a date, format: [YYYYMMDD] >>> ' d
    if [[ $d =~ ^[0-9]{8}$ ]]; then
        date -d "$d 2 days ago" '+%Y%m%d'
    else
        echo >&2 "Wrong input $d"
        exit 1
    fi
    

    Yields:

    20240222