shelllings

a practical way to learn shell
Log | Files | Refs | README | LICENSE

28_case.sh (1582B)


      1 #!/bin/sh
      2 
      3 # Instead of using if, elif, elif, elif, else, there's a more concise
      4 # (and often faster) method you can use; case.
      5 #
      6 # $ echo "Enter a letter: "
      7 # $ read user_input
      8 # $
      9 # $ case "$user_input" in
     10 # $ 	[a-z])
     11 # $ 		echo "Entered: lowercase"
     12 # $ 		;;
     13 # $ 	[A-Z])
     14 # $ 		echo "Entered: uppercase"
     15 # $ 		;;
     16 # $ 	[0-9])
     17 # $ 		echo "I said letter, not number"
     18 # $ 		;;
     19 # $ 	*) # for everything else
     20 # $ 		echo "What?"
     21 # $ 		;;
     22 # $ esac
     23 #
     24 # The snippet above should be self explanatory. Now, for other cases, it
     25 # can look like this
     26 #
     27 # $ case "$item" in
     28 # $ 	apple|banana|orange) # apple or banana or orange
     29 # $ 		echo "Food item"
     30 # $ 		;;
     31 # $ 	book)
     32 # $ 		echo "leisure item"
     33 # $ 		;;
     34 # $ 	*)
     35 # $ 		echo "unknown"
     36 # $ 		;;
     37 # $ esac
     38 #
     39 # It's better to use 'case' instead of 'if' when you are pattern
     40 # matching, which means you can avoid using grep. It can be better to
     41 # do 'if' instead of 'case' when there's arithmetic, like playing a 
     42 # hotter/colder game by having a user try to find a number.
     43 #
     44 # Below is the unfinished work of a rock-paper-scissors game between
     45 # a player and the computer
     46 
     47 choices="rock paper scissors"
     48 computer_choice=$(echo "$choices" | tr ' ' '\n' | shuf -n 1)
     49 printf "Choose rock paper or scissors: "
     50 read player_choice
     51 
     52 # The code snippet above needs no changing.
     53 # Have all the echo statements be just those 3 words exactly
     54 case "$player_choice" in
     55 	rock)
     56 		case "$computer_choice" in
     57 			rock) echo "tie" ;; # this is a valid way of condensing code
     58 			paper) echo "lost" ;;
     59 			scissors) echo "won" ;;
     60 	*)
     61 		echo "ERROR invalid option"
     62 		;;
     63 esac