一:脚本格式

1.1 指定解析器

脚本以 #!/bin/bash 开头,指定使用bash解析脚本;

1.2 新建 bash 脚本

  • 创建一个bash脚本,输出 hello world;
1
2
3
[root@hadoop100 shell]# cat hello.txt 
#!/bin/bash
echo "hello world"

二:执行方式

2.1 采用 bash 或 sh + 脚本的相对路径或绝对路径(不用赋予脚本+x 权限)

(1)sh + 脚本的相对路径

1
2
3
4
[root@hadoop100 shell]# sh ./hello.txt 
hello world
[root@hadoop100 shell]# sh hello.txt
hello world

(2)sh + 脚本的绝对路径

1
2
3
4
[root@hadoop100 shell]# pwd
/root/RupertTears/shell
[root@hadoop100 shell]# sh /root/RupertTears/shell/hello.txt
hello world

(3)bash + 脚本的相对路径

1
2
3
4
[root@hadoop100 shell]# bash ./hello.txt 
hello world
[root@hadoop100 shell]# bash hello.txt
hello world

(4)bash + 脚本的绝对路径

1
2
3
4
[root@hadoop100 shell]# pwd
/root/RupertTears/shell
[root@hadoop100 shell]# bash /root/RupertTears/shell/hello.txt
hello world

2.2 采用输入脚本的绝对路径或相对路径执行脚本(必须具有可执行权限+x)

(1)绝对路径

1
2
3
4
5
6
7
8
9
10
11
12
[root@hadoop100 shell]# pwd
/root/RupertTears/shell
[root@hadoop100 shell]# ls
hello.txt
[root@hadoop100 shell]# /root/RupertTears/shell/hello.txt
-bash: /root/RupertTears/shell/hello.txt: 权限不够
[root@hadoop100 shell]# chmod +x hello.txt
[root@hadoop100 shell]# ll
总用量 4
-rwxr-xr-x. 1 root root 31 12月 11 14:56 hello.txt
[root@hadoop100 shell]# /root/RupertTears/shell/hello.txt
hello world

(2)相对路径

1
2
[root@hadoop100 shell]# ./hello.txt 
hello world

2.3 在脚本的路径前加上“.”或者 source

(1)新建脚本文件

1
2
3
4
[root@hadoop100 shell]# cat test.sh 
#!/bin/bash
A=97
echo $A

(2)采用 bash 或 sh + 脚本路径,执行脚本文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
[root@hadoop100 shell]# ll
总用量 8
-rwxr-xr-x. 1 root root 31 12月 11 14:56 hello.txt
-rw-r--r--. 1 root root 25 12月 11 15:13 test.sh
[root@hadoop100 shell]# echo $A

[root@hadoop100 shell]# bash test.sh
97
[root@hadoop100 shell]# echo $A

[root@hadoop100 shell]# sh test.sh
97
[root@hadoop100 shell]# echo $A

(3)采用脚本的绝对路径或者相对路径,执行脚本文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[root@hadoop100 shell]# chmod +x test.sh 
[root@hadoop100 shell]# ll
总用量 8
-rwxr-xr-x. 1 root root 31 12月 11 14:56 hello.txt
-rwxr-xr-x. 1 root root 25 12月 11 15:13 test.sh
[root@hadoop100 shell]# ./test.sh
97
[root@hadoop100 shell]# echo $A

[root@hadoop100 shell]# pwd
/root/RupertTears/shell
[root@hadoop100 shell]# /root/RupertTears/shell/test.sh
97
[root@hadoop100 shell]# echo $A

(4)采用 source 或 “.” 执行

1
2
3
4
5
6
7
8
9
10
11
12
13
[root@hadoop100 shell]# source test.sh 
97
[root@hadoop100 shell]# echo $A
97
[root@hadoop100 shell]# vim test.sh
[root@hadoop100 shell]# cat test.sh
#!/bin/bash
A=99
echo $A
[root@hadoop100 shell]# . test.sh
99
[root@hadoop100 shell]# echo $A
99

三:执行方式的区别

  • 采用 bash 或者 sh + 脚本路径执行,本质上是在当前的 shell 中,打开了一个子 shell 来执行脚本,bash 解析器来执行该脚本,所以脚本本身不需要执行权限;当脚本执行完毕后,子 shell 关闭,回到父 shell 中;
  • 采用脚本的绝对路径或相对路径,本质上是脚本需要自己执行,所以需要执行权限;
  • 采用 “.”或者 source 的方式,使脚本在当前的shell中执行,无需打开子 shell !这就是为什么我们每次修改完 /etc/profile 文件后,需要 source 一下的原因。
  • 开启子 shell 与不开启子 shell 的区别就在于环境变量的继承关系,若在子 shell 中设置当前变量,在父 shell 中是不可见的。