case Statement The case statement provides a way to avoid using if..then..else statements. It allows users to enter a text string, then evaluate that string and provide the option that the string indicates. The case statement is matched against a number of values until a match is found. When a match is found, the commands are executed until the double semicolons “;;” are reached. Then those commands after the “esac” are executed. If there is no match it executes the commands after the “*)” until the double semicolons. The “*)” acts the same way as the “else” in a if ...then clause.
Lesson 13 | Lesson 14
case $VARIABLE in match_1) commands_to_execute ;; match_2) commands_to_execute ;; match_3) commands_to_execute ;; *) Optional Information commands_to_execute_for_no_match ;; esac
term_color.sh This simple script can be run in a tty to that you can change the color to be more easily read. Note that the tty uses 8 colors so you will not get the most beautiful output. The 8 clors are; black, white, red, blue,green, yellow, magenta, and cyan.
#!/bin/bash
echo -n "Choose Background Color for Terminal(b-black,g-grey,y-yellow): " read color case "$color" in b) setterm -background black -foreground white -store ;; g) setterm -background white -foreground black -store ;; y) setterm -background yellow -foreground red -store ;; *) echo "I do not understand" ;; esac
These lines provide text to help the user make a choice on color. When the user enters the choice it is read into the variable color.
echo -n "Choose Background Color for Terminal(b-black,g-grey,y-yellow): " read color
The case command is differentiated by the letter that was entered to create the variable "color" and followed by a ")" to indicate that is the option. Note the case variable captures the user choice for background and then executes a command that not only sets the background but also sets the forground color as well. The "-store" makes it a change until it is returned to the normal setting by "b" choice for a black background. Each option executes the command that follows until it reaches the ";;" or esac.
case "$color" in b) setterm -background black -foreground white -store ;; g) setterm -background white -foreground black -store ;; y) setterm -background yellow -foreground red -store ;;
This takes all entries that do not fit the three specified and indicates to the user they have made an error.
*) echo "I do not understand"
Copyright CyberMontana Inc. and BeginLinux.com
All rights reserved. Cannot be reproduced without written permission. Box 1262 Trout Creek, MT 59874
|