Master Linux Shell Flow Control: If, For, While, Case & Select with Examples
This guide explains Linux shell's flow‑control constructs—including conditional if/elif/else, loops (for, while, until), and selection statements (case, select) —by detailing their syntax, usage rules, and providing complete script examples that demonstrate each construct in action.
Shell Conditional Statements (if)
The if statement in a Linux shell follows the structure
if [[ condition ]]; then ... elif [[ condition ]]; then ... else ... fi. Conditions are evaluated using test operators such as -gt, -lt, etc. Example:
#!/bin/sh
scores=40
if [[ $scores -gt 90 ]]; then
echo "very good!"
elif [[ $scores -gt 80 ]]; then
echo "good!"
elif [[ $scores -gt 60 ]]; then
echo "pass!"
else
echo "no pass!"
fiRunning the script prints the appropriate message based on the value of scores. The double‑bracket [[ ]] syntax and spaces around variables are required.
Shell Loop Statements
for Loop
The classic for loop iterates over a list of words or the output of seq:
#!/bin/sh
for i in $(seq 10); do
echo $i;
doneThis prints numbers 1 through 10, each on a new line. An alternative C‑style syntax is for (( init; condition; increment )):
#!/bin/sh
for ((i=1; i<=10; i++)); do
echo $i;
donewhile Loop
The while loop repeats as long as its condition is true:
#!/bin/sh
i=10
while [[ $i -gt 5 ]]; do
echo $i;
((i--));
doneOutput: 10 9 8 7 6 (each on a separate line).
until Loop
The until loop runs until its condition becomes true:
#!/bin/sh
a=10
until [[ $a -lt 0 ]]; do
echo $a;
((a--));
doneResult: counts down from 10 to 0.
Shell Selection Statements
case Statement
The case construct matches a variable against patterns:
case $1 in
start|begin)
echo "start something";;
stop|end)
echo "stop something";;
*)
echo "Ignorant";;
esacRunning testcase.sh start prints start something.
select Statement
selectcreates a simple menu from a list of items, usually combined with case to handle the choice:
#!/bin/sh
select ch in "begin" "end" "exit"; do
case $ch in
"begin") echo "start something";;
"end") echo "stop something";;
"exit") echo "exit"; break;;
*) echo "Ignorant";;
esac
doneThe user selects a number; the script executes the corresponding branch.
These examples cover the three categories of shell flow‑control statements—conditional, looping, and selection—providing the essential syntax and practical scripts for everyday automation tasks.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
ITPUB
Official ITPUB account sharing technical insights, community news, and exciting events.
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.
