# Shell脚本入门

# 脚本格式

脚本以#!/bin/bash开头(指定解析器)

# 第一个Shell脚本:helloworld

(1)需求:创建一个Shell脚本,输出helloworld

(2)案例实操:

[bigdata@hadoop01 datas]$ touch helloworld.sh
[bigdata@hadoop01 datas]$ vim helloworld.sh
1
2

在helloworld.sh中输入如下内容

#!/bin/bash
echo "hello world bigdata"
1
2

(3)脚本的常用执行方式

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

  • sh+脚本的相对路径
[bigdata@hadoop01 datas]$ sh helloworld.sh 
hello world bigdata
1
2
  • sh+脚本的绝对路径
[bigdata@hadoop01 datas]$ sh /home/bigdata/datas/helloworld.sh 
hello world bigdata
1
2
  • bash+脚本的相对路径
[bigdata@hadoop01 datas]$ bash helloworld.sh 
hello world bigdata
1
2
  • bash+脚本的绝对路径
[bigdata@hadoop01 datas]$ bash /home/bigdata/datas/helloworld.sh 
hello world bigdata
1
2

第二种:采用输入脚本的绝对路径或相对路径执行脚本(必须具有可执行权限+x),相当于自己调用自己

(a)首先要赋予helloworld.sh 脚本的+x权限

[bigdata@hadoop01 datas]$ ll
总用量 4
-rw-rw-r--. 1 bigdata bigdata 39 118 22:44 helloworld.sh
[bigdata@hadoop01 datas]$ chmod 764 helloworld.sh #或者chmod u+x helloworld.sh
1
2
3
4

(b)执行脚本

  • 相对路径
[bigdata@hadoop01 datas]$ ./helloworld.sh
hello world bigdata
1
2
  • 绝对路径
[bigdata@hadoop01 datas]$ /home/bigdata/datas/helloworld.sh 
hello world bigdata
1
2

注意:第一种执行方法,本质是bash解析器帮你执行脚本,所以脚本本身不需要执行权限。第二种执行方法,本质是脚本需要自己执行,所以需要执行权限。

# 第二个Shell脚本:多命令处理

(1)需求:

​ 在/home/bigdata/目录下创建一个banzhang.txt,在banzhang.txt文件中增加“I love cls”。

(2)案例实操:

[bigdata@hadoop01 ~]$ touch batch.sh
[bigdata@hadoop01 ~]$ vim batch.sh
1
2

在batch.sh中输入如下内容

#!/bin/bash
cd /home/bigdata
touch banzhang.txt
echo "I love cls" >> banzhang.txt
1
2
3
4

查看结果

[bigdata@hadoop01 ~]$ ll
总用量 8
-rw-rw-r--. 1 bigdata bigdata 11 118 23:04 banzhang.txt
-rwxrw-r--. 1 bigdata bigdata 82 118 23:03 batch.sh
drwxrwxr-x. 2 bigdata bigdata 27 118 22:44 datas
[bigdata@hadoop01 ~]$ cat banzhang.txt 
I love cls
1
2
3
4
5
6
7