shell的选择语句分支

面向过程的语句结构:

  • 顺序结构:逐条运行
  • 选择结构:两个或以上的,满足条件时只会执行其中一个满足条件的分支
  • 循环结构:某循环体需要执行多次

If语句分支

if单分支

1
2
3
4
5
if [[ condition1 ]] ; then
# statements1
# statements2
# ...........
fi
1
2
3
4
5
if ([[ condition1 ]] ) then
# statements1
# statements2
# ...........
fi

if双分支

1
2
3
4
5
6
7
if [[ condition1 ]] ; then
# statements1
# statements2
else
# statements3
# ..........
fi

if多分支

1
2
3
4
5
6
7
8
if [[ condition1 ]] ; then
# statements1
# statements2
elif [[ condition2 ]] ; then
# statements3
elif [[ condition3 ]] ; then
# statements4
fi
1
2
3
4
5
6
7
8
9
10
11
if [[ condition1 ]] ; then
# statements1
# statements2
elif [[ condition2 ]] ; then
# statements3
elif [[ condition3 ]] ; then
# statements4
else
# statements5
# ..........
fi

select语句分支

select 表达式是 bash 的一种扩展应用,擅长于交互式场合。用户可以从一组不同的值中进行选择

语法格式

1
2
3
4
5
select varname in "string1" "string2" ; do
# statements1
# statements2
# .....
done

示例

1
2
3
4
5
6
#!/bin/bash
echo "What is your favourite OS?"
select var in "Linux" "Gnu Hurd" "Free BSD" "Other" ; do
break ;
done
echo "You have selected $var"

运行结果

1
2
3
4
5
6
7
What is your favourite OS?
1) Linux
2) Gnu Hurd
3) Free BSD
4) Other
#? 1
You have selected Linux

case语句分支

语法格式

1
2
3
4
5
6
7
8
9
10
11
12
case word in
pattern1)
# statements1
;;
pattern2)
# statements2
;;
# ..........
patternN)
# statementsN
;;
esac
  • case支持的globbing
1
2
3
4
*    # 任意长度的任意字符		
? # 任意单个字符
[] # 指定范围内的单个字符
a|b # a或者b
有钱任性,请我吃包辣条
0%