Unix script 9 - case

来源:互联网 发布:安全网络征文大赛 编辑:程序博客网 时间:2024/05/21 11:29
The case statement saves going through a whole set of if .. then .. else statements. Its syntax is really quitesimple:
talk.sh
#!/bin/shecho "Please talk to me ..."while :do  read INPUT_STRING  case $INPUT_STRING in        hello)                echo "Hello yourself!"                ;;        bye)                echo "See you again!"                break                ;;        *)                echo "Sorry, I don't understand"                ;;  esacdoneecho echo "That's all folks!"

Okay, so it's not the best conversationalist in the world; it's only anexample!

Try running it and check how it works...

$ ./talk.shPlease talk to me ...helloHello yourself!What do you think of politics?Sorry, I don't understandbyeSee you again!That's all folks!$
The syntax is quite simple:
The case line itself is always of the same format, and itmeans that we are testing the value of the variableINPUT_STRING.


The options we understand are then listed and followed by a right bracket,as hello) and bye).
This means that ifINPUT_STRING matches hello then that sectionof code is executed, up to the double semicolon.
If INPUT_STRING matches bye then the goodbyemessage is printed and the loop exits. Note that if we wanted to exitthe script completely then we would use the commandexit instead of break.
The third option here, the *), is the default catch-allcondition; it is not required, but is often useful for debugging purposeseven if we think we know what values the test variable will have.

The whole case statement is ended with esac (case backwards!)then weend the while loop with a done.

That's about as complicated as case conditions get, but they can be avery useful and powerful tool. They are often used to parse theparameters passed to a shell script, amongst other uses.


原创粉丝点击