- The $23 Echo Dot deal is a great deal to upgrade your smart home this Black Friday
- The newest Echo Show 8 just hit its lowest price ever for Black Friday
- 기술 기업 노리는 북한의 가짜 IT 인력 캠페인··· 데이터 탈취도 주의해야
- 구글 클라우드, 구글 워크스페이스용 제미나이 사이드 패널에 한국어 지원 추가
- The best MagSafe accessories of 2024: Expert tested and reviewed
Making a case for case statements on Linux
#!/bin/bash echo -n "enter the number of equal sides that the shape has> " read numsides # make sure answer is numeric re="^[0-9]+$" if ! [[ $numsides =~ $re ]] ; then echo "error: Not a number" >&2; exit 1 fi if [ $numsides -lt 3 ]; then echo "Sorry, but that would NOT be a geometric shape" elif [ $numsides == 3 ]; then echo triangle elif [ $numsides == 4 ]; then echo square or rectangle elif [ $numsides == 5 ]; then echo pentagon elif [ $numsides == 6 ]; then echo hexagon elif [ $numsides == 7 ]; then echo heptagon elif [ $numsides == 8 ]; then echo octagon elif [ $numsides == 9 ]; then echo nonagon elif [ $numsides == 10 ]; then echo decagon elif [ $numsides == 11 ]; then echo hendecagon elif [ $numsides == 12 ]; then echo dodecagon elif [ $numsides -gt 12 ]; then echo "Hmm, you’d better ask Google" fi
Using case statements, on the other hand, makes your code much simpler to put together and much easier to read.
#!/bin/bash echo -n "enter the number of equal sides that the shape has> " read numsides # make sure answer is numeric re="^[0-9]+$" if ! [[ $numsides =~ $re ]] ; then echo "error: Not a number" >&2; exit 1 fi case "$numsides" in 0-2) echo "Sorry, but that would NOT be a geometric shape";; 3) echo triangle;; 4) echo square or rectangle;; 5) echo pentagon;; 6) echo hexagon;; 7) echo heptagon;; 8) echo octogon;; 9) echo nonagon;; 10) echo decagon;; 11) echo hendecagon;; 12) echo dodecaggon;; *) echo "Hmm, you’d better ask Google" esac
Each segment in the case statement must end with two semicolons. However, you could use multiple commands separated by semicolons and only use the double semicolons at the end od that segment.
Wrap-up
Notice how much easier case commands are to set up and maintain. You can provide any number of possible values at the cost of one line each.