0

I want to write a bash script that reads a keyboard input (date dd:mm:yy), stores it in a variable then echoes back the Day it corresponds to, ie

Input : 03/08/2015

Output : Wednesday

I'm having some problems with formatting this, any help is much appreciated!!

  • 2
    Wednesday?? Also, is this a homework? – MatthewRock Sep 17 '15 at 13:15
  • 3rd of august is Monday – MatthewRock Sep 17 '15 at 13:18
  • 2
    You're having trouble formatting what? What do you have so far? – terdon Sep 17 '15 at 13:22
  • #!/bin/bash echo "Enter date in string form" #ex 22042005 read dat4 #date -jf "%Y%m%d%H%M%S" $dat4 "+date \"%A,%_d %B %Y %H:%M:%S\"" – bopi Sep 17 '15 at 13:45
  • 3
    Please edit your question to include more details. It is easy to miss and hard to read in the comments. See here for help on formatting your posts. – terdon Sep 17 '15 at 14:01
2

date accepts input with its -d flag, and prints it. However, input formatted like yours is treated like MM/DD/YYYY. But this shouldn't be too hard.

First, let's get input to variable:

read INPUT

Now, we need to change input from DD/MM/YYYY to MM/DD/YYYY. You can do that with sed and awk(you can also do that with awk:

INPUT=`echo $INPUT | awk -F '/' '{t=$1;$1=$2;$2=t;gsub(" ", "/");print;}'`

Now that INPUT is in proper format, feed it to date and make it only print the day:

date -d $INPUT +%A

Put it all together:

#!/bin/bash
read INPUT
INPUT=`echo $INPUT | awk -F '/' '{t=$1;$1=$2;$2=t;gsub(" ", "/");print;}'`
date -d $INPUT +%A
| improve this answer | |
  • Awk part isn't necessary, really – Sergiy Kolodyazhnyy Sep 17 '15 at 14:41
  • Run $ date --date='03/08/15' +%A and $ date --date='03/08/15' +%A – Sergiy Kolodyazhnyy Sep 17 '15 at 14:42
  • @Serg two same commands? Anyway, the command you gave gives wrong output – MatthewRock Sep 17 '15 at 14:46
  • 1
    @MathewRock Ah, I missed that OP needed European style input (day-month-year). OK, then it's correct. +1 – Sergiy Kolodyazhnyy Sep 17 '15 at 14:55
2

Perl has some nice built-in datetime modules:

$ perl -MTime::Piece -E '
     print "Input date (dd/mm/YYYY): ";
     chomp( $date = <> );
     $datetime = Time::Piece->strptime($date, "%d/%m/%Y");
     say $datetime->strftime("%e %B is a %A");
'
Input date (dd/mm/YYYY): 3/8/2015
 3 August is a Monday
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.