Henry
Henry

Reputation: 926

Manipulating user input

I'm new to bash. I am trying to get 2 inputs from the user in the form: DD/MM/YYYY DD/MM/YYYY(day,month,year in one line). Here is what I have tried for dd (I also will need to get MM and YYYY from both inputs):

dd1=read | cut -d'/' -f1 (I tried this with backquotes and it didn't work)

[do something with dd1 ...]

echo $dd1

$dd1 keeps coming up as empty. I could use some pointers (not specific answers) for my homework question. Thanks.

Upvotes: 0

Views: 172

Answers (3)

David W.
David W.

Reputation: 107080

Do you need to do this on one line, or do you want the user to INPUT two dates on one line?

If all you need is for the users to input two dates on the command line, you can do this:

read -p "Enter two dates in YY/MM/DD format: " date1 date2

Then, after the user enters in the two dates, you can parse them to verify that they're in the correct format. You can keep looping around until the dates are correct:

while 1
do
    read -p "Enter two dates in 'DD/MM/YYY' format: date1 date2
    if [ ! date1 ] -o [ ! date2 ]
    then
       echo "You need to enter two dates."
       sleep 2
       continue
    if
    [other tests to verify date formats...]
    break    # Passed all the tests
done

If you can input the dates one at a time, you can manipulate the IFS variable to use slashes instead of white spaces as separators.

OLDIFS="$IFS"   #Save the original
IFS="/"
read -p "Enter your date in MM/DD/YYYY format: " month day year
IFS="$OLDIFS"   #Restore the value of IFS

This could be put inside a while loop like the example above where you could verify the dates were entered in correctly.

Actually, you could do this:

OLDIFS="$IFS"   #Save the original
IFS="/ "   #Note space before quotation mark!
read -p "Enter two dates in MM/DD/YYYY format: " month1 day1 year1 month2 day2 year2
IFS="$OLDIFS"   #Restore the value of IFS
echo "Month #1 = $month1  Day #1 = $day1  Year #1 = $year1"
echo "Month #2 = $month1  Day #2 = $day2  Year #2 = $year2"

And get both dates on the same command line.

Upvotes: 0

Dennis Williamson
Dennis Williamson

Reputation: 360615

Give this a try. It will allow the user to type the date in and will split it for you on the slashes.

IFS=/ read -r -p "Enter a date in the form DD/MM/YYYY: " dd mm yy

Upvotes: 0

ismail
ismail

Reputation: 47672

You got it backwards, try like this;

read dd1 && echo $dd1|cut -d'/' -f1 

Upvotes: 2

Related Questions