Shell 基础

开始

第一行

1
#! /bin/bash

它代表的意思是,该文件使用的是bash语法。

默认我们用vim编辑的文档是不带有执行权限的,所以需要加一个执行权限chmod

1
chmod +x test.sh

使用sh命令去执行一个shell脚本的时候是可以加-x选项来查看这个脚本执行过程:sh -x test.sh

shell 脚本中的变量

1
2
3
4
5
6
d=`date "+%Y-%m-%d %H:%M:%S"`
echo "this script begin at $d"
echo "we will sleep 2 seconds."
sleep 2
d1=`date "+%Y-%m-%d %H:%M:%S"`
echo "the script end at $d1"

上述脚本中dd1作为变量出现,格式为:变量名=变量的值
使用变量时需要加上 “$” 符号。

执行结果:

1
2
3
this script begin at 2019-01-02 11:29:10
we will sleep 2 seconds.
the script end at 2019-01-02 11:29:12

数学运算

1
2
3
4
a=1
b=2
c=$[$a+$b]
echo "$a+$b is $c"

数学计算要用[ ]括起来并且外头要带一个”$”。脚本结果为:

1
1+2 is 3

与用户进行交互:

1
2
3
4
5
6
echo "请输入一个数字:"
read x
echo "请再输入一个数字:"
read y
sum=$[$x+$y]
echo "$x+$y 的和为:$sum"

结果为:

1
2
3
4
5
请输入一个数字:
1
请再输入一个数字:
2
1+2 的和为:3

更加简洁的方式,read -p 选项类似echo的作用。:

1
2
3
4
read -p "请输入一个数字:" x
read -p "请再输入一个人数字:" y
sum=$[$x+$y]
echo "$x+$y 的和为:$sum"

执行如下:

1
2
3
请输入一个数字:2
请再输入一个人数字:3
2+3 的和为:5

预设变量

1
2
sum=$[$1+$2]
echo $sum

执行时追加变量1和2:

1
$ sh pre_var.sh 1 2

输出结果:

1
3

shell脚本中的逻辑判断

基础用法

1. 不带 else

1
2
3
4
5
if 判断语句; then

一些条件语句

fi
1
2
3
4
read -p "Please input your score:" a
if ((a<60)) ; then
echo "You didn't pass the exam."
fi

输出:

1
2
Please input your score:56
You didn't pass the exam.

2. 带有 else

1
2
3
4
5
6
7
8
9
if 判断语句 ; then

command

else

command

fi

1
2
3
4
5
6
read -p "Please input your score:" a
if ((a<60)) ; then
echo "You didn't pass the exam."
else
echo "Good! You passed the exam."
fi

3. 带有 elif

1
2
3
4
5
6
7
8
9
10
11
12
13
if 判断语句一 ; then

command

elif 判断语句二; then

command

else

command

fi

if 判断档案属性

1
2
3
4
5
6
7
8
9
10
11
-e :判断文件或目录是否存在

-d :判断是不是目录,并是否存在

-f :判断是否是普通文件,并存在

-r :判断文档是否有读权限

-w :判断是否有写权限

-x :判断是否可执行

使用if判断时,具体格式为: if [ -e filename ] ; then

case

除了用if来判断逻辑外,还有一种常用的方式,那就是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
case 变量 in

value1)

command

;;

value2)

command

;;

value3)

command

;;

*)

command

;;

esac

上面的结构中,不限制value的个数,*则代表除了上面的value外的其他值。

shell脚本中的循环

for 基本语法

1
2
3
4
5
for 变量名 in 循环的条件; do

command

done

示例:(seq 1 5 表示从1到5的一个序列)

1
2
3
for i in `seq 1 5`;do
echo $i
done

输出:

1
2
3
4
5
1
2
3
4
5

while 基本语法

1
2
3
4
5
while 条件; do

command

done

shell脚本中的函数

基本语法

1
2
3
4
5
function 函数名() {

command

}

------ 本文结束 ------
0%