0

I have three variables $year $month and $day. Each of them gather the input from a user like: myday 20160303 or myday 2016 03 03 in different ways, I used multiple "if" statements to save in this example the first yyyy under year variable, mm under month and day accordingly. I need to use them to find out the day of the week. What I have at this moment is

nn=`date --date="$1" +"%A"`

echo "$nn"

It works with input like 20160404 but if the user type 3 arguments how can I use all three variables correctly in a date command to show the day of the week?

2 Answers 2

3

This should work in linux date version (GNU coreutils), not sure about Mac OS X. date.bash looks like this:

#!/bin/bash
date -d "$1$2$3" +%Y-%m-%d

assign exe permission :

chmod u+x date.bash

execute:

]# ./date.bash 2016 06 24
2016-06-24

]# ./date.bash 20160624
2016-06-24

]#./date.bash 2016 0624
2016-06-24

For Mac OS X, you can use the following syntax in date.bash

#!/bin/bash
date -j -f "%Y%m%d" "$1$2$3" +%Y-%m-%d

In all the above examples, I used +%Y-%m-%d for the format. You can replace that with +%A as you are doing to get the name of the day.

Note: For Mac OS, ./date.bash 2016-06-24 will not work, while in Linux it would work.

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

1 Comment

This has an extra advantage that if there are no arguments, it prints now :)
2

If you want to combine three arguments into one, it's simply:

"$1$2$3"

This will turn 2016 03 03 into 20160303

1 Comment

I was trying to put them in brackets but didn't think it is that easy, thank you

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.