← Linux and the Command Line
Lesson 47 of 51 · 10 XP
Choice: case
Theory and problem statement
Machine translation, not yet reviewed by a native speaker.
case compares a string with patterns — shorter and clearer than a long chain of elifs:
case "$1" in
start)
echo "Starting" ;;
stop|quit) # | — several options
echo "Stopping" ;;
*.txt) # patterns like for file names
echo "a text file" ;;
[0-9]*)
echo "starts with a digit" ;;
*) # everything else
echo "Usage: $0 start|stop" >&2
exit 1 ;;
esac
Each branch ends with ;;, and the whole block with esac (case backwards). The first branch that fits runs.
Classic service scripts (/etc/init.d/…) are built like this: service nginx start|stop|restart.
Task. The script determines the type of a file by the name from its argument and prints: image for .png, .jpg, .gif; code for .c, .py, .sh; archive for .zip, .tar.gz; unknown for everything else.
Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.