开发者

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=rea开发者_如何学编程d | 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.


You got it backwards, try like this;

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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜