BASH是Bourne Again SHell的缩写。它由Steve Bourne编写,作为原始Bourne Shell(由/ bin / sh表示)的替代品。它结合了原始版本的Bourne Shell的所有功能,以及其他功能,使其更容易使用。从那以后,它已被改编为运行Linux的大多数系统的默认shell。
if 分支结构
bash的if分支的基本语法结构如下:
1
2
3
4
5
6
7
|
if [ condition ]; then
<commands>
elif [ condition ]; then
<commands>
else
<commands>
fi
|
例如下面的一个示例:
1
2
3
4
5
6
7
8
9
10
|
#!/bin/bash
read -p "输入分数:" num
if [ $num -gt 90 ]; then
echo "你很优秀."
elif [ $num -lt 60 ]; then
echo "你该努力了."
else
echo "继续加油."
fi
|
运行脚本:
1
2
3
4
5
6
7
8
9
|
root@cfg-server:~/temp# ./score.sh
输入分数:95
你很优秀.
root@cfg-server:~/temp# ./score.sh
输入分数:76
继续加油.
root@cfg-server:~/temp# ./score.sh
输入分数:30
你该努力了.
|
while / until 循环结构
while循环可以定义为控制流语句,只要您所应用的条件为真,该语句就允许重复执行您给定的命令集。while循环的语法为:
1
2
3
4
5
6
7
|
while [ expression ]; do
command1
command2
. . .
. . . .
commandN
done
|
与 while 循环相反,until 循环在条件判断为false
时,循环执行一组命令。当判断首次为true
时,循环才会终止。
1
2
3
4
5
6
7
|
until [ expression ]; do
command1
command2
. . .
. . . .
commandN
done
|
下面是一个while循环的示例:
1
2
3
4
5
6
7
8
|
#!/bin/bash
# while-count: display a series of numbers
count=1
while [ $count -le 5 ]; do
echo $count
count=$((count + 1))
done
echo “Finished.”
|
case分支结构
case 语句通常用于简化具有多种不同选择的复杂条件语句,使 Bash 脚本更具可读性,并更易于维护。
下面是一个case使用的示例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
#!/bin/bash
# case-menu: a menu driven system information program
clear
echo ”
Please Select:
1. Display System Information
2. Display Disk Space
3. Display Home Space Utilization
0. Quit
”
read -p “Enter selection [0-3] > ”
case $REPLY in
0) echo “Program terminated.”
exit
;;
1) echo “Hostname: $HOSTNAME”
uptime
;;
2) df -h
;;
3) if [[ $(id -u) -eq 0 ]]; then
echo “Home Space Utilization (All Users)”
du -sh /home/*
else
echo “Home Space Utilization ($USER)”
du -sh $HOME
fi
;;
*) echo “Invalid entry” >&2
exit 1
;;
esac
|
for循环结构
bash的for循环与其他编程语言的for循环功能类似,只是语法稍异。
1
2
3
|
for variable [in words]; do
commands
done
|
例如下面的一个简单脚本:
1
2
3
4
|
#!/bin/bash
for i in {A..E}; do
echo $i
done;
|
执行后输入 A ~ E 的字符:
1
2
3
4
5
6
|
root@cfg-server:~/temp# ./fora.sh
A
B
C
D
E
|
另外,一些比较新的bash版本支持类似c,java等语言的for循环结构写法,如下:
1
2
3
4
|
#!/bin/bash
for ((i=0; i<5; i=i+1)); do
echo $i
done;
|
位置参数
通过位置参数,我们可以让程序访问命令行内容的 shell 。shell 提供了一个称为位置参数的变量集合,这个集合包含了命令行中所有独立的单词。这些变量按照从0到9给予命名。
比如下面的这个bash脚本 test.sh
:
1
2
3
4
5
6
7
|
#!/bin/bash
# test-param: script to view command line parameters
echo "\$0 = $0
\$1 = $1
\$2 = $2
\$3 = $3
\$4 = $4"
|
执行后效果:
1
2
3
4
5
6
7
8
9
10
11
12
|
root@cfg-server:~/temp# ./test.sh
$0 = ./test.sh
$1 =
$2 =
$3 =
$4 =
root@cfg-server:~/temp# ./test.sh a b c
$0 = ./test.sh
$1 = a
$2 = b
$3 = c
$4 =
|
可以看到 $n
表示命令行的第 n 个参数,其实 n 可以比较大。 另外 $#
表示参数的个数。