Shell Script Conditional Structures: Using if and case Statements
This article introduces shell script conditional structures, explains the syntax of if (single, double, and multi-branch) and case statements, and provides step‑by‑step examples including a grading script and a start/stop/restart command script with full Bash code.
Shell scripts are an essential skill for backend developers; this tutorial covers their conditional branching structures, focusing on if and case statements.
First, the basic script header is shown:
<code>#!/bin/bash</code>A simple "hello world" script demonstrates execution:
<code>#!/bin/bash
echo 'hello world'</code>The if statement in shell supports single‑branch, double‑branch, and multi‑branch forms. Examples of each syntax are provided:
<code># Single branch
if condition ; then
...
fi
# Double branch
if condition ; then
...
else
...
fi
# Multi‑branch
if condition ; then
...
elif other_condition ; then
...
else
...
fi</code>An example grading script reads a score, validates the input, and uses an if single‑branch to check format, then a multi‑branch to output comments such as "优秀", "良好", "一般", "及格" or "不及格".
<code>read -p "请输入成绩,成绩范围0-100: " score
if [ -z `echo $score | egrep '^[0-9]+$'` ]; then
echo "输入的成绩格式不正确"
fi
if ((score >= 90)); then
echo '优秀'
elif ((score >= 80)); then
echo '良好'
elif ((score >= 70)); then
echo '一般'
elif ((score >= 60)); then
echo '及格'
else
echo '不及格'
fi</code>The case statement provides another way to branch based on a variable's value. Its general form is shown:
<code>case $variable in
"value1")
# commands for value1
;;
"value2")
# commands for value2
;;
*)
# default commands
;;
esac</code>A practical case example handles command‑line arguments start , stop , and restart , printing corresponding messages or a usage hint.
<code>#!/bin/bash
case $1 in
"start")
echo "this code is start"
;;
"stop")
echo "this code is stop"
;;
"restart")
echo "this code is restart"
;;
*)
echo "Usage ${0} {start|stop|restart}"
;;
esac</code>php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.