一、shell程序的运行原理
Linux系统的shell作为操作系统的外壳,为用户提供使用操作系统的接口。它是命令语言、命令解释程序及程序设计语言的统称。
shell是用户和Linux内核之间的接口程序,如果把Linux内核想象成一个球体的中心,shell就是围绕内核的外层。当从shell或其他程序向Linux传递命令时,内核会做出相应的反应。
shell是一个命令语言解释器,它拥有自己内建的shell命令集,shell也能被系统中其他应用程序所调用。用户在提示符下输入的命令都由shell先解释然后传给Linux核心。
shell首先检查命令是否是内部命令,若不是再检查是否是一个应用程序(这里的应用程序可以是Linux本身的实用程序,如ls和rm,也可以是购买的商业程序,如xv,或者是自由软件,如emacs)。然后shell在搜索路径里寻找这些应用程序(搜索路径就是一个能找到可执行程序的目录列表)。如果键入的命令不是一个内部命令并且在路径里没有找到这个可执行文件,将会显示一条错误信息。如果能够成功找到命令,该内部命令或应用程序将被分解为系统调用并传给Linux内核。
shell的另一个重要特性是它自身就是一个解释型的程序设计语言,shell程序设计语言支持绝大多数在高级语言中能见到的程序元素,如函数、变量、数组和程序控制结构。shell编程语言简单易学,任何在提示符中能键入的命令都能放到一个可执行的shell程序中。
二、shell 变量
shell支持自定义变量
定义变量
定义变量时,变量名不加美元符号($),如:
[root@localhost ~]# variableName="value"
注意:变量名和等号之间不能有空格,这可能和你熟悉的所有编程语言都不一样.同时,变量名的命名须遵循如下规则:
#首个字符必须为字母(a-z,A-Z).
#中间不能有空格,可以使用下划线(_).
#不能使用标点符号.
#不能使用bash里的关键字(可用help命令查看保留关键字)。变量定义举例:
[root@localhost ~]# myUrl="http://www.baidu.com"
[root@localhost ~]# myNum=100
使用变量
使用一个定义过的变量,只要在变量名前面加美元符号($)即可,如:
[root@localhost ~]# your_name="tom"
[root@localhost ~]# echo $your_name
tom
[root@localhost ~]# echo ${your_name}
tom
[root@localhost ~]# 变量名外面的花括号是可选的,加不加都行,加花括号是为了帮助解释器识别变量的边界,比如下面这种情况:
[root@localhost ~]# for skill in Ada Coffe Action Java
> do
> echo "I am good at ${skill}Script"
> done
I am good at AdaScript
I am good at CoffeScript
I am good at ActionScript
I am good at Javascript
[root@localhost ~]#
如果不给skill变量加花括号,写成echo "I am good at $skillScript",解释器就会把$skillScript当成一个变量(其值为空),代码执行如果就不是我们期望的样子了。推荐给所有变量加上花括号,这是个好的编程习惯。
重新定义变量
已定义的变量,可以被重新定义,如:
[root@localhost ~]# myUrl="http://www.baidu.com"
[root@localhost ~]# echo ${myUrl}
http://www.baidu.com
[root@localhost ~]# myUrl="http://www.google.com"
[root@localhost ~]# echo ${myUrl}
http://www.google.com
[root@localhost ~]#这样写是合法的,但注意,第二次赋值的时候不能写$myUrl="http://www.google.com",使用变量的时候才加美元符($)。只读变量
使用readonly命令可以将变量定义为只读变量,只读变量的值不能被改变。
下面的例子尝试更改只读变量,结果报错:
#!/bin/bash
#
myUrl="http://www.baidu.com"
readonly myUrl
myUrl="http://www.google.com"运行脚本,结果如下:
[root@localhost ~]# ./readonly.sh
./readonly.sh: line 5: myUrl: readonly variable
删除变量
使用unset命令可以删除变量。语法:
[root@localhost ~]# echo $myUrl
http://www.google.com
[root@localhost ~]# unset myUrl
[root@localhost ~]# echo $myUrl
[root@localhost ~]#
变量被删除后不能再次使用;unset命令不能删除只读变量。
特殊变量
上面已经讲到,变量名只能包含数字,字母和下划线,因为某些包含其他字符的变量有特殊含义,这样的变量被称为特殊变量。
例如,$表示当前Shell进程的ID,即PID,看下面的代码:
[root@localhost ~]# echo $$
16523
[root@localhost ~]# 特殊变量列表变量 含义$0 当前脚本的文件名
$n 传递给脚本或函数的参数,n是一个数字,表示第几个参数。例如,第一个参数是$1,第二个参数是$2.
$# 传递给脚本或函数的参数个数.
$* 传递给脚本或函数的所有参数.
$@ 传递给脚本或函数的所有参数.被双引号("")包含时,与$*稍有不同,下面将会讲到.
$? 上个命令的退出状态,或函数的返回值.
$$ 当前Shell进程ID.对于Shell脚本,就是这些脚本所在的进程ID.
命令行参数
运行脚本传递给脚本的参数称为命令行参数.命令行参数用$n表示,例如,$1表示第一个参数,$2表示第二个参数,依次类推
请看下面的脚本:
#!/bin/bash
#
echo "File Name:$0"
echo "First Parameter:$1"
echo "First Parameter:$2"
echo "Quoted Values:$@"
echo "Quoted Values:$*"
echo "Total Number of Parameters:$#"运行结果:
[root@localhost test]# bash vis.sh du yong
File Name:vis.sh
First Parameter:du
First Parameter:yong
Quoted Values:du yong
Quoted Values:du yong
Total Number of Parameters:2
[root@localhost test]#
$*和$@的区别
$*和$@都表示传递给函数或脚本的所有参数,不被双引号("")包含时,都以"$1" "$2" ... "$n"的形式输出所有参数。
但是当它们被双引号("")包含时,"$*"会将所有的参数作为一个整体,以"$1 $2 ... $n"的形式输出所有参数;"$@"会将各个参数分开,以"$1" "$2" ... "$n"的形式输出所有参数。
下面的例子可以清楚的看到$*和$@的区别:
#!/bin/bash
#
echo "\$*=" $*
echo "\"\$*\"=" "$*"
echo "\$@=" $@
echo "\"\$@\"=" "$@"
echo "print each param from \$*"
for var in $*
doecho "$var"
done
echo "print each param from \$@"
for var in $@
doecho "$var"
done
echo "print each param from \"\$*\""
for var in "$*"
doecho "$var"
done
echo "print each param from \"\$@\""
for var in "$@"
doecho "$var"
done执行结果:
[root@localhost test]# bash teshu.sh 1 2 3 4
$*= 1 2 3 4
"$*"= 1 2 3 4
$@= 1 2 3 4
"$@"= 1 2 3 4
print each param from $*
1
2
3
4
print each param from $@
1
2
3
4
print each param from "$*" #加了双引号是一个整体
1 2 3 4
print each param from "$@" #加了双引号是多个字符
1
2
3
4
[root@localhost test]#
退出状态
$?可以获取上一个命令的退出状态.所谓退出状态,就是上一个命令执行后的返回结果
退出状态是一个数字,一般情况下,大部份命令执行成功会返回0,失败返回1.
不过,也有一些命令返回其他值,表示不同类型的错误.
下面例子中,命令成功执行:
[root@localhost test]# bash vis.sh du yong
File Name:vis.sh
First Parameter:du
First Parameter:yong
Quoted Values:du yong
Quoted Values:du yong
Total Number of Parameters:2
[root@localhost test]# echo $?
0
[root@localhost test]#$?也可以表示函数的返回值
环境变量
环境变量可以理解为bash作用域
本地变量:当前shell的进程
环境变量:当前shell进程及其子进程
局部变量:某个函数执行过程
本地变量示例:
[root@localhost ~]# myUrl="http://www.baidu.com"
[root@localhost ~]# echo $myUrl
http://www.baidu.com
[root@localhost ~]# bash 进入子shell
[root@localhost ~]# echo $myUrl #myUrl的值为空
[root@localhost ~]#
环境变量示例:
[root@localhost ~]# export myUrl="http://www.google.com" #定义环境变量
[root@localhost ~]# echo $myUrl
http://www.google.com
[root@localhost ~]# bash #进入子shell
[root@localhost ~]# echo $myUrl #myUrl的值还存在
http://www.google.com
[root@localhost ~]#
三、字符串
字符串是shell编程中最常用最有用的数据类型(除了数字和字符串,也没啥其它类型好用了),字符串可以用单引号,也可以用双引号。单双引号的区别如下:
单引号
[root@localhost test]# str='this is a string'
单引号字符串的限制:单引号里的任何字符都会原样输出,单引号字符串的变量是无效的;单引号字串中不能出现单引号(对单引号使用转义符后也不行)。
双引号
[root@localhost test]# your_name='zhangsan'
[root@localhost test]# str="Hello,I know your are \"$your_name\"! "
[root@localhost test]# echo $str
Hello,I know your are "zhangsan"!双引号的优点:双引号里可以有变量双引号里可以出现转义字符
拼接字符串
[root@localhost test]# echo $your_name
zhangsan
[root@localhost test]# greeting="hello,"$your_name"! "
[root@localhost test]# greeting_1="hello, ${your_name}! "
[root@localhost test]# echo $greeting $greeting_1
hello,zhangsan ! hello, zhangsan!
获取字符串长度
[root@localhost test]# string="abcdefg"
[root@localhost test]# echo ${#string}
7
提取子字符串
[root@localhost test]# string="alibaba is a great company"
[root@localhost test]# echo ${string:1:4}
liba
四、运算符
Bash支持很多运算符,包括算数运算符、关系运算符、布尔运算符、字符串运算符和文件测试运算符。
原生bash不支持简单的数学运算,但是可以通过其他命令来实现,例如awk和expr,expr最常用。
expr是一 款表达式计算工具,使用它能完成表达式的求值操作。
例如,两个数相加:
[root@localhost test]# vim tot.sh
[root@localhost test]# bash tot.sh
Total value:4
[root@localhost test]# 两点注意:表达式和运算符之前要有空格,例如2+2是不对的,必须写成2 + 2 ,这与我们熟悉的大多数编程语言不一样。
完整的表达式要被 ``包含,注意这个字符不是常用的单引号,在Esc键下边。
算术运算符
先来看一个使用算术运算符的例子:
#!/bin/bash
#
a=10
b=20
val=`expr $a + $b`
echo "a + b :$val"
val=`expr $a - $b`
echo "a - b : $val"
val=`expr $a \* $b`
echo "a * b : $val"
val=`expr $b / $a`
echo "b / a : $val"
val=`expr $b % $a`
echo "b % a : $val"
if [ $a == $b ]; thenecho "a is equal to b"
fi
if [ $a != $b ]; thenecho "a is not equal to b"
fi运行结果:
a + b :30
a - b : -10
a * b : 200
b / a : 2
b % a : 0
a is not equal to b注意:乘号(*)前边必须加反斜杠(\)才能实现乘法运算;运算符 说明 举例
+ 加法 `expr $a + $b` 结果为 30。
- 减法 `expr $a - $b` 结果为 10。
* 乘法 `expr $a \* $b` 结果为 200。
/ 除法 `expr $b / $a` 结果为 2。
% 取余 `expr $b % $a` 结果为 0。
= 赋值 a=$b 将把变量 b 的值赋给 a。
== 相等。用于比较两个数字,相同则返回 true。 [ $a == $b ] 返回 false。
!= 不相等。用于比较两个数字,不相同则返回 true。 [ $a != $b ] 返回 true。注意:条件表达式要放在方括号之间,并且要有空格,例如[$a==$b]是错误的,必须写成[ $a==$b ].
关系运算符
关系运算符只支持数字,不支持字符串,除非字符串的值是数字。
先来看一个关系运算符的例子:
#!/bin/bash
#
a=10
b=20
if [ $a -eq $b ]; thenecho "$a -eq $b : a is equal to b"
elseecho "$a -eq $b : a is not equal to b"
fi
if [ $a -ne $b ]; thenecho "$a -ne $b : a is not equal to b"
elseecho "$a -ne $b : a is equal to b"
fi
if [ $a -gt $b ]; thenecho "$a -gt $b : a is greater than b"
elseecho "$a -gt $b : a is not greater than b"
fi
if [ $a -lt $b ]; thenecho "$a -lt $b : a is less than b"
elseecho "$a -lt $b : a is not less than b"
fi
if [ $a -ge $b ]; thenecho "$a -ge $b : a is greater or equal to b"
elseecho "$a -ge $b : a is not greater or equal to b"
fi
if [ $a -le $b ]; thenecho "$a -le $b : a is less or equal to b"
elseecho "$a -le $b : a is not less or equal to b"
fi运行结果:
10 -eq 20 : a is not equal to b
10 -ne 20 : a is not equal to b
10 -gt 20 : a is not greater than b
10 -lt 20 : a is less than b
10 -ge 20 : a is not greater or equal to b
10 -le 20 : a is less or equal to b关系运算符列表
运算符 说明 举例
-eq 检测两个数是否相等,相等返回 true。 [ $a -eq $b ] 返回 true。
-ne 检测两个数是否相等,不相等返回 true。 [ $a -ne $b ] 返回 true。
-gt 检测左边的数是否大于右边的,如果是,则返回 true。 [ $a -gt $b ] 返回 false。
-lt 检测左边的数是否小于右边的,如果是,则返回 true。 [ $a -lt $b ] 返回 true。
-ge 检测左边的数是否大等于右边的,如果是,则返回 true。 [ $a -ge $b ] 返回 false。
-le 检测左边的数是否小于等于右边的,如果是,则返回 true。 [ $a -le $b ] 返回 true。
布尔运算符
先来看一个布尔运算符的例子:
#!/bin/bash
#
a=10
b=20
if [ $a != $b ]; thenecho "$a != $b : a is not equal to b"
elseecho "$a != $b : a is equal to b"
fi
if [ $a -lt 100 -a $b -gt 15 ]; thenecho "$a -lt 100 -a $b -gt 15 : returns true"
elseecho "$a -lt 100 -a $b -gt 15 : returns false"
fi
if [ $a -lt 100 -o $b -gt 100 ]; thenecho "$a -lt 100 -o $b -gt 100 : returns true"
elseecho "$a -lt 100 -o $b -gt 100 : returns false"
fi
if [ $a -lt 5 -o $b -gt 100 ]; thenecho "$a -lt 5 -o $b -gt 100 : returns true"
elseecho "$a -lt 5 -o $b -gt 100 : returns false"
fi运行结果:10 != 20 : a is not equal to b
10 -lt 100 -a 20 -gt 15 : returns true
10 -lt 100 -o 20 -gt 100 : returns true
10 -lt 5 -o 20 -gt 100 : returns false布尔运算符列表
运算符 说明 举例
! 非运算,表达式为 true 则返回 false,否则返回 true。 [ ! false ] 返回 true。
-o 或运算,有一个表达式为 true 则返回 true。 [ $a -lt 20 -o $b -gt 100 ] 返回 true。
-a 与运算,两个表达式都为 true 才返回 true。 [ $a -lt 20 -a $b -gt 100 ] 返回 false。
字符串运算符
先来看一个例子:
#!/bin/bash
#
a="abc"
b="efg"
if [ $a = $b ]; thenecho "$a = $b : a is equal to b"
elseecho "$a = $b : a is not equal to b"
fi
if [ $a != $b ]; thenecho "$a != $b : a is not equal to b"
elseecho "$a != $b : a is equal to b"
fi
if [ -z $a ]; thenecho "-z $a : string length is zero"
elseecho "-z $a : string length is not zero"
fi
if [ -n $a ]; thenecho "-n $a : string length is not zero"
elseecho "-n $a : string length is zero"
fi
if [ $a ]; thenecho "$a : string is not empty"
elseecho "$a : string is empty"
fi运行结果:
abc = efg : a is not equal to b
abc != efg : a is not equal to b
-z abc : string length is not zero
-n abc : string length is not zero
abc : string is not empty字符串运算符列表
运算符 说明 举例
= 检测两个字符串是否相等,相等返回 true。 [ $a = $b ] 返回 false。
!= 检测两个字符串是否相等,不相等返回 true。 [ $a != $b ] 返回 true。
-z 检测字符串长度是否为0,为0返回 true。 [ -z $a ] 返回 false。
-n 检测字符串长度是否为0,不为0返回 true。 [ -z $a ] 返回 true。
str 检测字符串是否为空,不为空返回 true。 [ $a ] 返回 true。
文件测试运算符
文件测试运算符用于检测文件的各种属性
例如,变量file表示文件 "/root/test/string.sh",它的大小为4.0K,具有644权限。下面的代码,将检测该文件的各种属性:
#!/bin/bash
#
file="/root/test/string.sh"
if [ -r $file ]; thenecho "File has read access"
elseecho "File does not have read access"
fi
if [ -w $file ]; thenecho "File has write permission"
elseecho "File does not have write permission"
fi
if [ -x $file ]; thenecho "File has execute permission"
elseecho "File does not have execute permission"
fi
if [ -f $file ]; thenecho "File is an ordinary file"
elseecho "This is sepcial file"
fi
if [ -d $file ]; thenecho "File is a directory"
elseecho "This is not a directory"
fi
if [ -s $file ]; thenecho "File size is not zero"
elseecho "File size is zero"
fi
if [ -e $file ]; thenecho "File exists"
elseecho "File does not exist"
fi运行结果:
[root@localhost test]# bash file.sh
File has read access
File has write permission
File does not have execute permission
File is an ordinary file
This is not a directory
File size is not zero
File exists文件测试运算符列表
操作符 说明 举例
-b file 检测文件是否是块设备文件,如果是,则返回 true。 [ -b $file ] 返回 false。
-c file 检测文件是否是字符设备文件,如果是,则返回 true。 [ -b $file ] 返回 false。
-d file 检测文件是否是目录,如果是,则返回 true。 [ -d $file ] 返回 false。
-f file 检测文件是否是普通文件(既不是目录,也不是设备文件),如果是,则返回 true。[ -f $file ] 返回 true。
-g file 检测文件是否设置了 SGID 位,如果是,则返回 true。 [ -g $file ] 返回 false。
-k file 检测文件是否设置了粘着位(Sticky Bit),如果是,则返回 true。 [ -k $file ] 返回 false。
-p file 检测文件是否是具名管道,如果是,则返回 true。 [ -p $file ] 返回 false。
-u file 检测文件是否设置了 SUID 位,如果是,则返回 true。 [ -u $file ] 返回 false。
-r file 检测文件是否可读,如果是,则返回 true。 [ -r $file ] 返回 true。
-w file 检测文件是否可写,如果是,则返回 true。 [ -w $file ] 返回 true。
-x file 检测文件是否可执行,如果是,则返回 true。 [ -x $file ] 返回 true。
-s file 检测文件是否为空(文件大小是否大于0),不为空返回 true。 [ -s $file ] 返回 true。
-e file 检测文件(包括目录)是否存在,如果是,则返回 true。 [ -e $file ] 返回 true。
五、流程控制
if ...else 语句
if语句通过关系运算符判断表达式的真假来决定执行哪个分支。Shell有三种if...else语句;
if ...fi 语句;
if ...else ...fi 语句;
if ...elif ...else ...fi 语句;
if ... else 语句的语法:if [ expression ]thenStatement(s) to be executed if expression is truefi如果 expression 返回 true,then 后边的语句将会被执行;如果返回 false,不会执行任何语句。最后必须以 fi 来结尾闭合 if,fi 就是 if 倒过来拼写,后面也会遇见。注意:expression 和方括号([ ])之间必须有空格,否则会有语法错误。#!/bin/bash
#
a=10
b=20
if [ $a == $b ]
thenecho "a is equal to b"
fi
if [ $a != $b ]
thenecho "a is not equal to b"
fi运行结果:
a is not equal to b
if ...else ... fi 语句
if ...else ...fi 语句的语法:
if [ expression ]
thenStatement(s) to be executed if expression is true
elseStatement(s) to be executed if expression is not true
fi如果expression返回true,那么then后边的语句将会被执行;否则,执行else后边的语句。举个例子:
#!/bin/bash
#
a=10
b=20
if [ $a == $b ];thenecho "a is equal to b"
elseecho "a is not equal to b"
fi执行结果:
a is not equal to b
if ...elif ...else ...fi语句
if ...elif ...else ...fi语句可以对多个条件进行判断,语法为:
if [ expression 1 ]
thenStatement(s) to be executed if expression 1 is true
elif [ expression 2 ]
thenStatement(s) to be executed if expression 2 is true
elif [ expression 3 ]
thenStatement(s) to be executed if expression 3 is true
elseStatement(s) to be executed if no expression is true
fi哪一个expression值为true,就执行哪个expression后面的语句;如果都为false,那么不执行任何语句。
举个例子:
#!/bin/bash
#
a=10
b=20
if [ $a == $b ];thenecho "a is equal to b"
elif [ $a -gt $b ];thenecho "a is greater than b"
elif [ $a -lt $b ];thenecho "a is less than b"
elseecho "None of the condition met"
fi运行结果:
a is less than bif ...else语句也可以写成一行,以命令的方式来运行,像这样:
[root@localhost test]# if test $[2*3] -eq $[1+5];then echo 'The twonumbers are equal!'; fi;
The twonumbers are equal!if ...else语句也经常与test命令结合使用,如下所示:
num1=$[2*3]
num2=$[1+5]
if test $[num1] -eq $[num2]
thenecho 'The two numbers are equal!'
elseecho 'The two numbers are not equal!'
fi输出: The two numbers are equal!
test 命令用于检查某个条件是否成立,与方括号([ ])类似。
for循环语句
与其他编程语言类似,Shell支持for循环
for循环一般格式为:
for 变量 in 列表
docommand1command2...commandN
done
列表是一组值(数字、字符串等)组成的序列,每个值通过空格分隔。每循环一次,就将列表中的下一个值赋给变量。
in列表是可选的,如果不用它,for循环使用命令行的位置参数。
例如,顺序输出当前列表中的数字:
[root@localhost test]# for loop in 1 2 3 4 5
> do
> echo "The value is:$loop"
> done
The value is:1
The value is:2
The value is:3
The value is:4
The value is:5
[root@localhost test]#
顺序输出字符串中的字符:
[root@localhost test]# for str in 'This is a string'
> do
> echo $str
> done
This is a string
[root@localhost test]#
显示主目录下以.bash开头的文件:
#!/bin/bash
#
for FILE in $HOME/.bash*
doecho $FILE
done运行结果:
[root@localhost test]# bash for_bash.sh
/root/.bash_history
/root/.bash_logout
/root/.bash_profile
/root/.bashrc
while循环语句
while循环用于不断执行一系列命令,也用于从输入文件中读取数据;命令通常为测试条件。其格式为:
while command
doStatement(s) to be executed if command is true
done
命令执行完毕,控制返回循环顶部,从头开始直至测试条件为假。
以下是一个基本的while循环,测试条件是:如果COUNTER小于5,那么返回true。COUNTER从0开始以,每次循环处理时,COUNTER加1.运行上述脚本,返回数字1到5,然后终止。
#!/bin/bash
#
COUNTER=0
while [ $COUNTER -lt 5 ]
doCOUNTER=` expr $COUNTER + 1`echo $COUNTER
done运行脚本,输出:
[root@localhost test]# bash while.sh
1
2
3
4
5
while循环可用于读取键盘信息。下面的例子中,输入信息被设置为变量FILM,按
echo 'type 运行脚本,输出类似下面: type until循环语句 until循环执行一系列命令直至条件为true时停止。until循环与while循环在处理方式上刚好相反,一般while循环优于until循环,但在某些时候,也只是极少数情况下,until循环更加有用。 until循环模式为: until command 运行结果: 0 case ...esac语句 case ...esac与其他语言中的switch ...case语句类似,是一种多分枝选择结构。 case语句匹配一个值或一个模式,如果匹配成功,执行相匹配的命令。case语句模式如下: case 值 in case工作方式如上所示。取值后面必须为关键字in,每一模式必须以右括号结束。取值可以为变量或常数。匹配发现取值符合某一模式后,其间所有命令开始执行直至;;。;;与其他语言中的break类似,意思是跳到整个case语句的最后。 取值将检测匹配的每一模式。一旦模式匹配,则执行完匹配模式相应命令后不再继续其他模式。如果无一匹配模式,使用星号*捕获该值,再执行后面的命令。 下面的脚本提示输入1到4,与每一种模式进行匹配: #!/bin/bash 输入不同的内容,会有不同的结果,例如: Input a number between 1 to 4 再举一个例子: #!/bin/bash 运行结果: [root@localhost test]# bash case1.sh break和continue命令 在循环过程中,有时候需要在未达到循环结束条件时强制跳出循环,像大多数编程语言一样,Shell也使用break和continue来跳出循环。 break命令 break命令允许跳出所有循环(终止执行后面的所有循环)。 下面的例子中,脚本进入死循环直至用户输入数字大于5.要跳出这个循环,返回到shell提示符下,就要使用break命令。 #!/bin/bash 在嵌套循环中,break命令后面还可以跟一个整数,表示跳出第几层循环,例如: break n 表示跳出第n层循环。 下面是一个嵌套循环的例子,如果var1等于2,并且var2等于0,就跳出循环: #!/bin/bash 如上,break2表示直接跳出外层循环。运行结果: 1 0 continue命令 continue命令与break命令类似,只有一点差别,它不会跳出所有循环,仅仅跳出当前循环。 对上面的例子进行修改: #!/bin/bash 运行代码发现,当输入大于5的数字时,该例中的循环不会结束,语句 echo "Game is over!" 永远不会被执行。 同样,continue后面也可以跟一个数字,表示跳出第几层循环。 再看一个continue的例子: #!/bin/bashNUMS="1 2 3 4 5 6 7"for NUM in $NUMS 运行结果: Found odd number 数组 Shell在编程方面比Windows批处理强大很多,无论是在循环、运算 bash支持一维数组(不支持多维数组),并且没有限定数组的大小。类似与C语言,数组元素的下标由0开始编号。获取数组中的元素要利用下标,下标可以是整数或算术表达式,其值应大于或等于0。 定义数组 在shell中,用括号来表示数组,数组元素用“空格”符号分割开,定义数组的一般形式为: array_name=(value1 ...valuen) 例如: array_name=(value0 value1 value2 value3) 还可以单独定义数组的各个分量: array_name[0]=value0 可以不使用连续的下标,而且下标的范围没有限制。 读取数组 读取数组元素值的一般格式是: ${array_name[index]} 例如: valuen=${array_name[2]} 举个例子: #!/bin/shNAME[0]="Zara" 运行结果: First Index: Zara 使用@或*可以获取数组中的所有元素,例如: ${array_name[*]} 举个例子: #!/bin/shNAME[0]="Zara" 运行结果: First Method: Zara Qadir Mahnaz Ayan Daisy 获取数组的长度 获取数组长度的方法与获取字符串长度的方法相同,例如: # 取得数组元素的个数 六、函数 函数可以让我们将一个复杂功能划分成若干模块,让程序结构更加清晰,代码重复利用率更高,像其他编程语言一样,Shell也支持函数,Shell函数必须先定义后使用。 Shell函数的定义格式如下: function_name () {list of commands[ return value ] 如果你愿意,也可以在函数名前加上关键字fuction: function function_name () {list of commands[ return value ] 函数返回值,可以显式增加return语句;如果不加,会将最后一条命令运行结果作为返回值。 Shell函数返回值只能是整数,一般用来表示函数执行成功与否,0表示成功,其他值表示失败,如果return其他数据,比如一个字符串,往往会得到错误提示:”numeric argument required“. 如果一定要让函数返回字符串,那么可以先定义一个变量,用来接收函数的计算结果,脚本在需要的时候访问这个变量来获得函数返回值。 先来看一个例子: #!/bin/bash# Define your function here 运行结果: $./test.sh 调用函数只需要给出函数名,不需要加括号。 再来看一个带有return语句的函数: #!/bin/bash 运行结果: The function is to get the sum of two numbers... 函数返回值在调用该函数后通过$?来获得。 再来看一个函数嵌套例子: #!/bin/bash# Calling one function from another 运行结果: Url_1 is http://see.xidian.edu.cn/cpp/shell/ 像删除变量一样,删除函数也可以用unset命令,不过要加上.f选项,如下所示: $unset .f function_name 如果你希望直接从终端调用函数,可以将函数定义在主目录下的.profile文件,这样每次登录后,在命令提示符后面输入函数名字就可以立即调用。 函数参数 在Shell中,调用函数时可以向其传递参数,在函数体内部,通过$n的形式来获取参数的值,例如,$1表示第一个参数,$2表示第二个参数... 带参数的函数示例: #!/bin/bash 运行脚本: #!/bin/bash 注意,$10不能获取第十个参数,获取第十个参数需要${10}.当n>=10时,需要使用${n}来获取参数。 另外,还有几个特殊变量用来处理参数,前面已经提到: 特殊变量 说明$# 传递给函数的参数个数。
echo -n 'enter your most liked film: '
while read FILM
doecho "Yeah! great film the $FILM"
done
enter your most liked film: Sound of Music
Yeah! great film the Sound of Music
doStatement(s) to be executed until command is true
donecommand 一般为条件表达式,如果返回值为false,则继续执行循环体内的语句,否则跳出循环。
例如,使用until命令输出0~9的数字:
#!/bin/basha=0until [ ! $a -lt 10 ]
doecho $aa=`expr $a + 1`
done
1
2
3
4
5
6
7
8
9
模式1)command1command2command3;;
模式2)command1command2command3;;
*)command1command2command3;;
esac
#
echo 'Input a number between 1 to 4'
echo 'Your number is:\c'
read aNum
case $aNum in1) echo 'You select 1';;2) echo 'You select 2';;3) echo 'You select 3';;4) echo 'You select 4';;*) echo 'You do not select a number between 1 to 4';;
esac
Your number is:3
You select 3
#
option="${1}"
case ${option} in-f) FILE="${2}"echo "File name is $FILE";;-d) DIR="${2}"echo "Dir name is $DIR";;*)echo "`basename ${0}`:usage: [-f file] | [-d directory]"exit 1 # Command to come out of the program with status 1;;
esac
case1.sh:usage: [-f file] | [-d directory]
[root@localhost test]# bash case1.sh -f index.jsp
File name is index.jsp
[root@localhost test]# bash case1.sh -d linux
Dir name is linux
[root@localhost test]#
#
while :
doecho -n "Input a number between 1 to 5:"read aNumcase $aNum in1|2|3|4|5) echo "Your number is $aNum!";;*) echo "You do not select a number between 1 to 5,game is over!"break;;esac
done
#
for var1 in 1 2 3
dofor var2 in 0 5doif [ $var1 -eq 2 -a $var2 -eq 0 ]; thenbreak 2elseecho "$var1 $var2"fidone
done
1 5
while :
doecho -n "Input a number between 1 to 5: "read aNumcase $aNum in1|2|3|4|5) echo "Your number is $aNum!";;*) echo "You do not select a number between 1 to 5!"continueecho "Game is over!";;esac
done
doQ=`expr $NUM % 2`if [ $Q -eq 0 ]thenecho "Number is an even number!!"continuefiecho "Found odd number"
done
Number is an even number!!
Found odd number
Number is an even number!!
Found odd number
Number is an even number!!
Found odd number
array_name[1]=value1
array_name[2]=value2
NAME[1]="Qadir"
NAME[2]="Mahnaz"
NAME[3]="Ayan"
NAME[4]="Daisy"
echo "First Index: ${NAME[0]}"
echo "Second Index: ${NAME[1]}"
Second Index: Qadir
${array_name[@]}
NAME[1]="Qadir"
NAME[2]="Mahnaz"
NAME[3]="Ayan"
NAME[4]="Daisy"
echo "First Method: ${NAME[*]}"
echo "Second Method: ${NAME[@]}"
Second Method: Zara Qadir Mahnaz Ayan Daisy
length=${#array_name[@]}
# 或者
length=${#array_name[*]}
# 取得数组单个元素的长度
lengthn=${#array_name[n]}
}
}
Hello () {echo "Url is http://see.xidian.edu.cn/cpp/shell/"
}# Invoke your function
Hello
Hello World
$
funWithReturn(){echo "The function is to get the sum of two numbers..."echo -n "Input first number: "read aNumecho -n "Input another number: "read anotherNumecho "The two numbers are $aNum and $anotherNum !"return $(($aNum+$anotherNum))
}
funWithReturn
# Capture value returnd by last command
ret=$?
echo "The sum of two numbers is $ret !"
Input first number: 25
Input another number: 50
The two numbers are 25 and 50 !
The sum of two numbers is 75 !
number_one () {echo "Url_1 is http://see.xidian.edu.cn/cpp/shell/"number_two
}number_two () {echo "Url_2 is http://see.xidian.edu.cn/cpp/u/xitong/"
}number_one
Url_2 is http://see.xidian.edu.cn/cpp/u/xitong/
funWithParam(){echo "The value of the first parameter is $1 !"echo "The value of the second parameter is $2 !"echo "The value of the tenth parameter is $10 !"echo "The value of the tenth parameter is ${10} !"echo "The value of the eleventh parameter is ${11} !"echo "The amount of the parameters is $# !" # 参数个数echo "The string of the parameters is $* !" # 传递给函数的所有参数
}
funWithParam 1 2 3 4 5 6 7 8 9 34 73
funWithParam(){echo "The value of the first parameter is $1 !"echo "The value of the second parameter is $2 !"echo "The value of the tenth parameter is $10 !"echo "The value of the tenth parameter is ${10} !"echo "The value of the eleventh parameter is ${11} !"echo "The amount of the parameters is $# !" # 参数个数echo "The string of the parameters is $* !" # 传递给函数的所有参数
}
funWithParam 1 2 3 4 5 6 7 8 9 34 73
$* 显示所有传递给函数的参数。
$@ 与$*相同,但是略有区别,请查看Shell特殊变量。
$? 函数的返回值。