Shell脚本是一个包含一系列命令序列的文本文件。当运行这个脚本文件时,文件中包含的命令序列将得到执行。(展示、运行hello.sh)
语法:
shell脚本的第一行必须如下格式:
#!/bin/sh
符号 #!用来指定该脚本文件的解析程序。在上面例子中使用/bin/sh来解析该脚本。当编辑好脚本后,如果要执行该脚本,还必须使其具有可执行属性。chmod +x filename
注释:
在进行shell编程时,以#开头的句子表示注释,直到这一行的结束。如果使用了注释,即使相当长的时间内没有使用该脚本,也能在很短的时间内明白该脚本的作用及工作原理。
变量:
shell编程中,所有的变量都由字符串组成,并且不需要预先对变量进行声明,
例:s1
#!/bin/sh
#set variable a
a="hello wold"
#print a
echo "A is:"
echo $a
变量
有时候变量名很容易与其他文字混淆。例
S2
num=2
echo "this is the $numnd"
思考:输出?why?
num=2
echo "this is the $numnd"
这并不会打印出"this is the 2nd",而仅仅打印"this is the ",因为shell会去搜索变量numnd的值,但是这个变量时没有值的。可以使用花括号来告诉shell我们打印的是num的变量:
num=2
echo "this is the ${num}nd"
这将打印:this is the 2nd
默认变量
$#:传人脚本的命令行参数个数
$*:所有命令行参数值,在各个参数值之间留有空格
$0:命令本身(shell文件名)
$1:第一个命令行参数
$2:第二个命令行参数
S3
#!/bin/sh
echo "number of vars:"$#
echo "number of vars:"$*
echo "number of vars:"$1
echo "number of vars:"$2
echo "number of vars:"$3
echo "number of vars:"$4
运行./s2 1 2 3 4
输出结果:?
局部变量
在变量首次被赋值时加上local关键字可以声明一个局部变量,
例:S4:
#!/bin/bash
hello="var2"
echo $hello
function func1 {
local hello ="var2"
echo $hello
}
func1
echo $hello
输出?
变量(注意)
1、变量赋值时,在“=”左右两边都不能有空格
2、BASH中的语句结尾不需要分号
If语句
if [ expression ]
then
#code block
fi
if [ expression ]
then
#code block
else
#code block
fi
if [ expression ]
then
#code block
else if [ expression ]
then
#code block
else
#code block
fi
fi
if [ expression ];then
#code block
elif [ expression ]
then
#code block
else
#code block
fi
fi
例:
比较整数a和b是否相等: if [ $a = $b ]
判断整数a是否大于整数b:if [ $a -gt $b ]
比较字符串a和b是否相等:if [ $a =$b ]
判断字符串a是否为空: if [ -z $a ]
判断整数变量a是否大于b :if [ $a -gt $b ]
注意:
1、在“[”和"]"符号的左右都留有空格
2、“=”左右都有空格
判断
-e文件已经存在
-f文件是普通文件
-s文件大小不为零
-d文件是一个目录
-r文件对当前用户可以读取
-w文件对当前用户可以写入
-x文件对当前用户可以执行
例:S5
#!/bin/sh
folder=/home
[ -r "$folder" ] && echo "Can read $folder"
[ -f "$folder" ] || echo "this is not file"
For循环
for循环结构与C语言中有所不同,在BASH中for循环的基本结构是
for var in [ list ]
do
#code block
done
其中$var 是循环控制变量,[ list ]s是var需要遍历的一个集合,do/done 对包含了循环体,相当于C语言中的一对大括号。另外如果do和for被写在同一行,必须在do前面加上“;”
如:for $var in [ list ];do例:S6
#!/bin/bash
for day in sun mon tue wed thu fri sat
do
echo $day
done
如果列表被包含在一对双引号中,则被认为是一个元素,如
#!/bin/bash
for day in "sun mon tue wed thu fri sat"
do
echo $day
done
For循环(注意)上面的例子中,在for所在那行,变量day是没有加"$"符号的,而在循环体内,在echo所在行变量$day是必须加上"$"符号的。
while循环
while循环的基本结构是:
while [ condition ]
do
#code block
done
until 循环
until循环的结构是
until [ condition ]
do
#code block
done
while和until的区别在与while是为真时执行,until是为假时执行Case语句
BASH中的case结构与C语言中的switch语句的功能比较类似,可以用于进行多项分支控制。
case "$var" in
condition1 )
;;
condition )
;;
*)
default statments;;
esac
Case语句
例S7
#!/bin/bash
echo "Hi a key ,then hit return."
read Keypress
case "$Keypress" in
[A-Z] ) echo "Uppercase letter";;
[a-z] ) echo "Lowercase letter";;
[0-9] ) echo "Digit";;
* ) echo "Punctuation,whitespace,or other";;
esac