1. 条件语句 - if-else:
if [ condition ]; then
# commands for true condition
else
# commands for false condition
fi
例如:
#!/bin/bash
read -p "Enter a number: " num
if [ $num -gt 0 ]; then
echo "The number is positive."
elif [ $num -eq 0 ]; then
echo "The number is zero."
else
echo "The number is negative."
fi
2. 循环语句 - for:
for variable in list; do
# commands
done
例如:
#!/bin/bash
for fruit in apple banana cherry; do
echo "I like $fruit."
done
3. 循环语句 - while:
while [ condition ]; do
# commands
done
例如:
#!/bin/bash
count=1
while [ $count -le 5 ]; do
echo "Count: $count"
count=$((count + 1))
done
4. 循环语句 - until:
until [ condition ]; do
# commands
done
例如:
#!/bin/bash
count=1
until [ $count -gt 5 ]; do
echo "Count: $count"
count=$((count + 1))
done
5. case语句:
case expression in
pattern1)
# commands
;;
pattern2)
# commands
;;
*)
# default commands
;;
esac
例如:
#!/bin/bash
read -p "Enter a fruit: " fruit
case $fruit in
apple)
echo "It's a red fruit."
;;
banana)
echo "It's a yellow fruit."
;;
*)
echo "I don't know this fruit."
;;
esac
6. 跳出循环 - break 和 continue:
- break: 跳出当前循环。
- continue: 跳过当前循环的剩余部分,继续下一次迭代。
#!/bin/bash
for num in {1..5}; do
if [ $num -eq 3 ]; then
break # 跳出循环
fi
echo "Number: $num"
done
for num in {1..5}; do
if [ $num -eq 3 ]; then
continue # 跳过当前循环迭代
fi
echo "Number: $num"
done
这些是一些基本的Shell流程控制结构。根据实际需求,你可以组合使用这些结构来实现不同的逻辑。流程控制是编写Shell脚本时非常重要的一部分,它决定了程序的执行流程和逻辑。
转载请注明出处:http://www.pingtaimeng.com/article/detail/3288/Linux