📙
📙
📙
📙
Shell
搜索文档…
流程控制

IF-ELSE

if 语句语法格式:
1
if condition1
2
then
3
command1
4
elif condition2
5
then
6
command2
7
else
8
commandN
9
fi
Copied!
也可以写为
1
if condition1;then
2
command1
3
elif condition2;then
4
command2
5
else
6
commandN
7
fi
Copied!

示例

1
a=10
2
b=20
3
if [ $a == $b ];then
4
echo "a 等于 b"
5
elif [ $a -gt $b ];then
6
echo "a 大于 b"
7
elif [ $a -lt $b ];then
8
echo "a 小于 b"
9
else
10
echo "没有符合的条件"
11
fi
Copied!

for 循环

for循环一般格式为:
1
for var in item1 item2 ... itemN
2
do
3
command1
4
command2
5
...
6
commandN
7
done
Copied!
也可以写为
1
for var in item1 item2 ... itemN;do
2
command1
3
command2
4
...
5
commandN
6
done
Copied!
写成一行:
1
for var in item1 item2 ... itemN; do command1; command2… done;
Copied!

示例

1
for loop in 1 2 3 4 5
2
do
3
echo "The value is: $loop"
4
done
5
# 输出
6
The value is: 1
7
The value is: 2
8
The value is: 3
9
The value is: 4
10
The value is: 5
Copied!
1
for str in This is a string
2
do
3
echo $str
4
done
5
# 输出
6
This
7
is
8
a
9
string
Copied!
最近更新 9mo ago