1

I am new to shell scripting.. I want a script to get any date as a input from user and print date of 3 days back?

example: If user enters date as 2013-01-01 then output should be

2012-12-29.

2 Answers 2

3

If you have GNU date, then this will work:

user_date=2013-01-01
date +%Y-%m-%d -d "$user_date - 3 days"

With BSD date, you'd have to do like this:

user_date=2013-01-01
date -j -v -3d +%Y-%m-%d -d "${user_date//-}0000"

because BSD date needs date to be in the format YYYYmmddHHMM.

I don't have a Solaris now to test there. If you're in Solaris then hopefully there is gdate, and you can use the first option, just replace the date command with gdate.

Whichever OS you are in, there are two important points:

  1. In what format can you pass dates to the date command. I tested that GNU date can accept YYYY-mm-dd format (and probably many others), while BSD needs YYYYmmddHHMM.
  2. In what format can you ask for a difference. With GNU date simply DATE - 3 days works, with BSD date it's trickier with -j -v -3d flags.

man date of your system should help you get through these hurdles. In the worst case, you could do all the date operations you need in perl or similar.

Sign up to request clarification or add additional context in comments.

Comments

1

You can just do:

date --date="3 days ago"

to get get date of 3 days back.

2 Comments

He needs to get -3 days relative to some other date coming from user input.
Oh ok, +1 to your answer then :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.