学习文章来源文本来源 Linux Shell脚本教程:30分钟玩转Shell脚本编程。 文章名字很霸气,30分钟学会,看了一下目录,内容不是很多,基本覆盖shell编程基础,例如:变量,流程控制和函数等,没有awk等高阶用发介绍,努力一把,三十多分钟应该能过一遍。但是,我这里不打算这样玩,还是想认真看一下基础,这一块断断续的也看过一些,总是容易忘。打算全面建立一个系统的映象,因此规划时间是一个月。

后面会有可能会记录一些比较。进度在此打卡。

目录结构

  • Shell简介
  • Shell对于运维人员的重要性
  • 几种常见的Shell
  • 如何进入Shell
  • Shell提示符
  • 第一个Shell脚本
  • Shell变量
  • Shell特殊变量
  • Shell替换
  • Shell运算符
  • Shell注释
  • Shell字符串
  • Shell数组
  • Shell echo命令
  • shell printf命令
  • Shell if else语句
  • Shell test命令
  • Shell case esac语句
  • Shell for循环
  • Shell while循环
  • Shell until循环
  • Shell跳出循环
  • Shell函数
  • Shell函数参数
  • Shell输入输出重定向
  • Shell文件包含

笔记

查看当前shell

1
2
3
4

cat /etc/shells # 查看当前系统支持的shell类型
echo $SHELL     # 查看当前默认使用的shell程序

Bash shell 提示符可以包含的要素

字符 描述
\a 铃声字符
\d 格式为“日 月 年”的日期
\e ASCII转义字符
\h 本地主机名
\H 完全合格的限定域主机名
\j shell当前管理的作业数
\1 shell终端设备名的基本名称
\n ASCII换行字符
\r ASCII回车
\s shell的名称
\t 格式为“小时:分钟:秒”的24小时制的当前时间
\T 格式为“小时:分钟:秒”的12小时制的当前时间
\@ 格式为am/pm的12小时制的当前时间
\u 当前用户的用户名
\v bash shell的版本
\V bash shell的发布级别
\w 当前工作目录
\W 当前工作目录的基本名称
\! 该命令的bash shell历史数
\# 该命令的命令数量
\$ 如果是普通用户,则为美元符号$;如果超级用户(root 用户),则为井号#。
\nnn 对应于八进制值 nnn 的字符
\\ 斜杠
\[ 控制码序列的开头
\] 控制码序列的结尾

helloworld

1
2
#!/bin/bash
echo "Hello World !"

变量使用

 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
33
34
35
36
37
# 等号周围不能包含有空格
# 若value中包含有
url=https://blog.jeffreysun.net

# 若果包含有空格,需要用引号包围起来
author='jeffrey sun'

# 变量使用

echo $url
echo This is ${author}\'s blog
# 加括号有助于编译器区分变量的边界

# 单引号 包围会原样输出,即使包含有变量和命令
echo 'my blog url is ${url}'
# my blog url is ${url}


# 双引号 输出时会先解析里面的变量和命令
echo "my blog url is ${url}"
# my blog url is https://blog.jeffreysun.net


#将命令的结果赋值给变量
variable=`command`
variable=$(command)


#只读变量
myUrl="http://see.xidian.edu.cn/cpp/shell/"
readonly myUrl


# 删除变量
unset variable_name


特殊变量

变量 含义
$0 当前脚本的文件名
$n 传递给脚本或函数的参数。n 是一个数字,表示第几个参数。例如,第一个参数是$1,第二个参数是$2。
$# 传递给脚本或函数的参数个数。
$* 传递给脚本或函数的所有参数。
$@ 传递给脚本或函数的所有参数。被双引号(” “)包含时,与 $* 稍有不同,下面将会讲到。
$? 上个命令的退出状态,或函数的返回值。
$$ 当前Shell进程ID。对于 Shell 脚本,就是这些脚本所在的进程ID。

$* 和 $@ 都表示传递给函数或脚本的所有参数,不被双引号(” “)包含时,都以"$1” “$2” … “$n” 的形式输出所有参数。

但是当它们被双引号(” “)包含时,“$*” 会将所有的参数作为一个整体,以"$1 $2 … $n"的形式输出所有参数;“$@” 会将各个参数分开,以"$1” “$2” … “$n” 的形式输出所有参数。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
echo "File Name: $0"
echo "First Parameter : $1"
echo "First Parameter : $2"
echo "Quoted Values: $@"
echo "Quoted Values: $*"
echo "Total Number of Parameters : $#"


# bash cmd.sh Zara Ali
# File Name: cmd.sh
# First Parameter : Zara
# First Parameter : Ali
# Quoted Values: Zara Ali
# Quoted Values: Zara Ali
# Total Number of Parameters : 2

shell替换

转义字符 含义
\\ 反斜杠
\a 警报,响铃
\b 退格(删除键)
\f 换页(FF),将当前位置移到下页开头
\n 换行
\r 回车
\t 水平制表符(tab键)
\v 垂直制表符

命令替换

命令替换是指Shell可以先执行命令,将输出结果暂时保存,在适当的地方输出。语法:

1
2
`command`
#注意是反引号,不是单引号,这个键位于 Esc 键下方。

例子:

1
2
3
4
5
6
7
#!/bin/bash
DATE=`date`
echo "Date is $DATE"
USERS=`who | wc -l`
echo "Logged in user are $USERS"
UP=`date ; uptime`
echo "Uptime is $UP"

运行结果:

1
2
3
4
Date is Thu Sep  5 22:32:38 CST 2019
Logged in user are        1
Uptime is Thu Sep  5 22:32:38 CST 2019
22:32  up 14 days, 1 hr, 1 user, load averages: 2.17 1.80 1.51

变量替换

变量替换可以根据变量的状态(是否为空、是否定义等)来改变它的值,可以使用的变量替换形式:

形式 说明
${var} 变量本来的值
${var:-word} 如果变量 var 为空或已被删除(unset),那么返回 word,但不改变 var 的值。
${var:=word} 如果变量 var 为空或已被删除(unset),那么返回 word,并将 var 的值设置为 word。
${var:?message} 如果变量 var 为空或已被删除(unset),那么将消息 message 送到标准错误输出,可以用来检测变量 var 是否可以被正常赋值。若此替换出现在Shell脚本中,那么脚本将停止运行。
${var:+word} 如果变量 var 被定义,那么返回 word,但不改变 var 的值。

例子:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#!/bin/bash

echo ${var:-"Variable is not set"}
echo "1 - Value of var is ${var}"

echo ${var:="Variable is not set"}
echo "2 - Value of var is ${var}"

unset var
echo ${var:+"This is default value"}
echo "3 - Value of var is $var"

var="Prefix"
echo ${var:+"This is default value"}
echo "4 - Value of var is $var"

echo ${var:?"Print this message"}
echo "5 - Value of var is ${var}"

运行结果:

1
2
3
4
5
6
7
8
9
Variable is not set
1 - Value of var is
Variable is not set
2 - Value of var is Variable is not set
3 - Value of var is
This is default value
4 - Value of var is Prefix
Prefix
5 - Value of var is Prefix

运算符

 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
#!/bin/sh

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 ]
then
   echo "a is equal to b"
fi

if [ $a != $b ]
then
   echo "a is not equal to b"
fi

运行结果:

1
2
3
4
5
6
a + b : 30
a - b : -10
a * b : 200
b / a : 2
b % a : 0
a is not equal to b

注意:

  • 乘号(*)前边必须加反斜杠(\)才能实现乘法运算;
  • if...then...fi 是条件语句,后续将会讲解

算术运算表

运算符 说明 举例
+ 加法 `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。

关系运算符

 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
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/bin/sh

a=10
b=20
if [ $a -eq $b ]
then
   echo "$a -eq $b : a is equal to b"
else
   echo "$a -eq $b: a is not equal to b"
fi

if [ $a -ne $b ]
then
   echo "$a -ne $b: a is not equal to b"
else
   echo "$a -ne $b : a is equal to b"
fi

if [ $a -gt $b ]
then
   echo "$a -gt $b: a is greater than b"
else
   echo "$a -gt $b: a is not greater than b"
fi

if [ $a -lt $b ]
then
   echo "$a -lt $b: a is less than b"
else
   echo "$a -lt $b: a is not less than b"
fi

if [ $a -ge $b ]
then
   echo "$a -ge $b: a is greater or  equal to b"
else
   echo "$a -ge $b: a is not greater or equal to b"
fi

if [ $a -le $b ]
then
   echo "$a -le $b: a is less or  equal to b"
else
   echo "$a -le $b: a is not less or equal to b"
fi

关系运算符列表

运算符 说明 举例
-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。

布尔运算符

 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/sh

a=10
b=20

if [ $a != $b ]
then
   echo "$a != $b : a is not equal to b"
else
   echo "$a != $b: a is equal to b"
fi

if [ $a -lt 100 -a $b -gt 15 ]
then
   echo "$a -lt 100 -a $b -gt 15 : returns true"
else
   echo "$a -lt 100 -a $b -gt 15 : returns false"
fi

if [ $a -lt 100 -o $b -gt 100 ]
then
   echo "$a -lt 100 -o $b -gt 100 : returns true"
else
   echo "$a -lt 100 -o $b -gt 100 : returns false"
fi

if [ $a -lt 5 -o $b -gt 100 ]
then
   echo "$a -lt 100 -o $b -gt 100 : returns true"
else
   echo "$a -lt 100 -o $b -gt 100 : returns false"
fi

运行结果:

1
2
3
4
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

字符串运算符

 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
33
34
35
36
37
38
39
#!/bin/sh

a="abc"
b="efg"

if [ $a = $b ]
then
   echo "$a = $b : a is equal to b"
else
   echo "$a = $b: a is not equal to b"
fi

if [ $a != $b ]
then
   echo "$a != $b : a is not equal to b"
else
   echo "$a != $b: a is equal to b"
fi

if [ -z $a ]
then
   echo "-z $a : string length is zero"
else
   echo "-z $a : string length is not zero"
fi

if [ -n $a ]
then
   echo "-n $a : string length is not zero"
else
   echo "-n $a : string length is zero"
fi

if [ $a ]
then
   echo "$a : string is not empty"
else
   echo "$a : string is empty"
fi

运行结果:

1
2
3
4
5
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

文件测试运算符

操作符 说明 举例
-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

字符串

单引号

  • 单引号里的任何字符都会原样输出,单引号字符串中的变量是无效的
  • 单引号字串中不能出现单引号(对单引号使用转义符后也不行)

双引号

  • 双引号里可以有变量
  • 双引号里可以出现转义字符

拼接字符串

1
2
3
4
5
6
#!/bin/bash

your_name="jeffrey"
greeting="hello, "$your_name" !"
greeting_1="hello, ${your_name} !"
echo $greeting $greeting_1

运行结果:

1
hello, jeffrey ! hello, jeffrey !

获取字符串长度

1
2
string="abcd"
echo ${#string} #输出 4

提取子字符串

1
2
string="jeffrey\'s blog"
echo ${string:1:4} #输出effr

~~查找子字符串~~

教程有误

1
2
string="alibaba is a great company"
echo `expr index "$string" is`

数组

 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
#!/bin/bash

# 数组定义
array_name=(value0 value1 value2 value3)

# 或者
array_name=(
value0
value1
value2
value3
)

# 或者单独定义
NAME[0]="Zara"
NAME[1]="Qadir"
NAME[2]="Mahnaz"
NAME[3]="Ayan"
NAME[4]="Daisy"
echo "First Index: ${NAME[0]}"
echo "Second Index: ${NAME[1]}"
echo "First Method: ${NAME[*]}"
echo "Second Method: ${NAME[@]}"

# 取得数组元素的个数
length=${#array_name[@]}
# 或者
length=${#array_name[*]}
# 取得数组单个元素的长度
lengthn=${#array_name[n]}

prinft

printf 命令的语法:

1
printf  format-string  [arguments...]

这里仅说明与C语言printf()函数的不同:

  • printf 命令不用加括号
  • format-string 可以没有引号,但最好加上,单引号双引号均可。
  • 参数多于格式控制符(%)时,format-string 可以重用,可以将所有参数都转换。
  • arguments 使用空格分隔,不用逗号。
 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
# format-string为双引号
$ printf "%d %s\n" 1 "abc"
1 abc
# 单引号与双引号效果一样
$ printf '%d %s\n' 1 "abc"
1 abc
# 没有引号也可以输出
$ printf %s abcdef
abcdef
# 格式只指定了一个参数,但多出的参数仍然会按照该格式输出,format-string 被重用
$ printf %s abc def
abcdef
$ printf "%s\n" abc def
abc
def
$ printf "%s %s %s\n" a b c d e f g h i j
a b c
d e f
g h i
j
# 如果没有 arguments,那么 %s 用NULL代替,%d 用 0 代替
$ printf "%s and %d \n"
and 0
# 如果以 %d 的格式来显示字符串,那么会有警告,提示无效的数字,此时默认置为 0
$ printf "The first program always prints'%s,%d\n'" Hello Shell
-bash: printf: Shell: invalid number
The first program always prints 'Hello,0'
$

if-else 语句

if-else

语句结构

 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

if [ expression ]
then
   Statement(s) to be executed if expression is true
fi

if [ expression ]
then
   Statement(s) to be executed if expression is true
else
   Statement(s) to be executed if expression is not true
fi

if [ expression 1 ]
then
   Statement(s) to be executed if expression 1 is true
elif [ expression 2 ]
then
   Statement(s) to be executed if expression 2 is true
elif [ expression 3 ]
then
   Statement(s) to be executed if expression 3 is true
else
   Statement(s) to be executed if no expression is true
fi

其他常用方式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14

# if 写在同一行
if test $[2*3] -eq $[1+5]; then echo 'The two numbers are equal!'; fi;

# 与test结合一起使用
num1=$[2*3]
num2=$[1+5]
if test $[num1] -eq $[num2]
then
    echo 'The two numbers are equal!'
else
    echo 'The two numbers are not equal!'
fi

test的基本用法

 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
# 数组
num1=100
num2=100
if test $[num1] -eq $[num2]
then
    echo 'The two numbers are equal!'
else
    echo 'The two numbers are not equal!'
fi

# 字符串
num1=100
num2=100
if test num1=num2
then
    echo 'The two strings are equal!'
else
    echo 'The two strings are not equal!'
fi

# 文件
cd /bin
if test -e ./bash
then
    echo 'The file already exists!'
else
    echo 'The file does not exists!'
fi

数值测试

参数 说明
-eq 等于则为真
-ne 不等于则为真
-gt 大于则为真
-ge 大于等于则为真
-lt 小于则为真
-le 小于等于则为真

字符串测试

参数 说明
= 等于则为真
!= 不相等则为真
-z 字符串 字符串长度伪则为真
-n 字符串 字符串长度不伪则为真

文件测试

参数 说明
-e 文件名 如果文件存在则为真
-r 文件名 如果文件存在且可读则为真
-w 文件名 如果文件存在且可写则为真
-x 文件名 如果文件存在且可执行则为真
-s 文件名 如果文件存在且至少有一个字符则为真
-d 文件名 如果文件存在且为目录则为真
-f 文件名 如果文件存在且为普通文件则为真
-c 文件名 如果文件存在且为字符型特殊文件则为真
-b 文件名 如果文件存在且为块特殊文件则为真

case esac语句

case语句格式

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
case 值 in
模式1)
    command1
    command2
    command3
    ;;
模式2)
    command1
    command2
    command3
    ;;
*)
    command1
    command2
    command3
    ;;
esac

for循环

for循环一般格式

1
2
3
4
5
6
7
for 变量 in 列表
do
    command1
    command2
    ...
    commandN
done

例子

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17

for loop in 1 2 3 4 5
do
    echo "The value is: $loop"
done

for str in 'This is a string'
do
    echo $str
done
# String 内容是一个整体

for FILE in $HOME/.bash*
do
   echo $FILE
done

while循环

while循环格式

1
2
3
4
while command
do
   Statement(s) to be executed if command is true
done

例子:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
COUNTER=0
while [ $COUNTER -lt 5 ]
do
    COUNTER='expr $COUNTER+1'
    echo $COUNTER
done

echo 'type <CTRL-D> to terminate'
echo -n 'enter your most liked film: '
while read FILM
do
    echo "Yeah! great film the $FILM"
done

until 循环

until 循环执行一系列命令直至条件为 true 时停止。until 循环与 while 循环在处理方式上刚好相反。一般while循环优于until循环,但在某些时候,也只是极少数情况下,until 循环更加有用。

until 循环格式为:

1
2
3
4
until command
do
   Statement(s) to be executed until command is true
done

例子:

1
2
3
4
5
6
a=0
until [ ! $a -lt 10 ]
do
   echo $a
   a=`expr $a + 1`
done

Shell break和continue命令

break命令允许跳出所有循环(终止执行后面的所有循环)。

 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
while :
do
    echo -n "Input a number between 1 to 5: "
    read aNum
    case $aNum in
        1|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

# 在嵌套循环中,break 命令后面还可以跟一个整数,表示跳出第几层循环

for var1 in 1 2 3
do
   for var2 in 0 5
   do
      if [ $var1 -eq 2 -a $var2 -eq 0 ]
      then
         break 2
      else
         echo "$var1 $var2"
      fi
   done
done

continue命令与break命令类似,只有一点差别,它不会跳出所有循环,仅仅跳出当前循环

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
while :
do
    echo -n "Input a number between 1 to 5: "
    read aNum
    case $aNum in
        1|2|3|4|5) echo "Your number is $aNum!"
        ;;
        *) echo "You do not select a number between 1 to 5!"
            continue
            echo "Game is over!"
        ;;
    esac
done

Shell函数:Shell函数返回值、删除函数、在终端调用函数

Shell 函数的定义格式如下:

1
2
3
4
function_name () {
    list of commands
    [ return value ]
}

如果你愿意,也可以在函数名前加上关键字 function:

1
2
3
4
function function_name () {
    list of commands
    [ return value ]
}

函数返回值,可以显式增加return语句;如果不加,会将最后一条命令运行结果作为返回值。

demo

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
#!/bin/bash
# Define your function here
Hello () {
   echo "Url is http://blog.jeffreysun.net/"
}
# Invoke your function
Hello

#####
# Url is http://blog.jeffreysun.net/
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
funWithReturn(){
    echo "The function is to get the sum of two numbers..."
    echo -n "Input first number: "
    read aNum
    echo -n "Input another number: "
    read anotherNum
    echo "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 !"

像删除变量一样,删除函数也可以使用 unset 命令,不过要加上 .f 选项,如下所示:

1
unset .f function_name

在Shell中,调用函数时可以向其传递参数。在函数体内部,通过 $n 的形式来获取参数的值,例如,$1表示第一个参数,$2表示第二个参数…

带参数的函数示例:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#!/bin/bash
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

#### 输出

# The value of the first parameter is 1 !
# The value of the second parameter is 2 !
# The value of the tenth parameter is 10 !
# The value of the tenth parameter is 34 !
# The value of the eleventh parameter is 73 !
# The amount of the parameters is 12 !
# The string of the parameters is 1 2 3 4 5 6 7 8 9 34 73 !"
特殊变量 说明
$# 传递给函数的参数个数。
$* 显示所有传递给函数的参数。
$@ 与$*相同,但是略有区别,请查看Shell特殊变量。
$? 函数的返回值。

Shell输入输出重定向:Shell Here Document,/dev/null文件

输出重定向, 语法为:command > file 输入重定向,语法为:command < file

一般情况下,每个 Unix/Linux 命令运行时都会打开三个文件:

  • 标准输入文件(stdin):stdin的文件描述符为0,Unix程序默认从stdin读取数据。
  • 标准输出文件(stdout):stdout 的文件描述符为1,Unix程序默认向stdout输出数据。
  • 标准错误文件(stderr):stderr的文件描述符为2,Unix程序会向stderr流中写入错误信息。

demo:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
# stderr 重定向到 file
$command 2 > file


# stderr 追加到 file 文件末尾
$command 2 >> file


# 将 stdout 和 stderr 合并后重定向到 file
$command > file 2>&1
# 或
$command >> file 2>&1


# command 命令将 stdin 重定向到 file1,将 stdout 重定向到 file2
$command < file1 >file2

全部可用的重定向命令列表

命令 说明
command > file 将输出重定向到 file。
command < file 将输入重定向到 file。
command » file 将输出以追加的方式重定向到 file。
n > file 将文件描述符为 n 的文件重定向到 file。
n » file 将文件描述符为 n 的文件以追加的方式重定向到 file。
n >& m 将输出文件 m 和 n 合并。
n <& m 将输入文件 m 和 n 合并。
« tag 将开始标记 tag 和结束标记 tag 之间的内容作为输入。

Here Document

语法:

1
2
3
command << delimiter
    document
delimiter

demo

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
wc -l << EOF
    This is a simple lookup program
    for good (and bad) restaurants
    in Cape Town.
EOF

# ### std
# 3

#  vi 编辑器将 document 保存到 test.txt 文件
filename=test.txt
vi $filename <<EndOfCommands
i
This file was created automatically from
a shell script
^[
ZZ
EndOfCommands

/dev/null 文件

如果希望执行某个命令,但又不希望在屏幕上显示输出结果,那么可以将输出重定向到 /dev/null

1
2
3
4
5

command > /dev/null

# 屏蔽 stdout 和 stderr
command > /dev/null 2>&1

Shell文件包含

像其他语言一样,Shell 也可以包含外部脚本,将外部脚本的内容合并到当前脚本。

Shell 中包含脚本可以使用:

1
. filename

1
source filename

两种方式的效果相同,简单起见,一般使用点号(.),但是注意点号(.)和文件名中间有一空格。

常用代码块

1
2
3
4

# 获取当前脚本所在目录
current_dir=$(cd "$(dirname "$0")";pwd)