Skip to content

Shell 概述

脚本格式

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

第一个 Shell 脚本:helloworld.sh

shell
[root@centos7 sh]$ touch helloworld.sh
[root@centos7 sh]$ vim helloworld.sh
 helloworld.sh 中输入如下内容
#!/bin/bash
echo "helloworld"

脚本的常用执行方式

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

sh+脚本的相对路径

shell
[root@centos7 sh]$ sh ./helloworld.sh
Helloworld

sh+脚本的绝对路径

shell
[root@centos7 sh]$ sh /home/atguigu/shells/helloworld.sh
helloworld

bash+脚本的相对路径

shell
[root@centos7 sh]$ bash ./helloworld.sh
Helloworld

bash+脚本的绝对路径

shell
[root@centos7 sh]$ bash /home/atguigu/shells/helloworld.sh
Helloworld

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

首先要赋予 helloworld.sh 权限

shell
[root@centos7 sh]$ bash /home/atguigu/shells/helloworld.sh
Helloworld

执行脚本 相对路径

shell
[root@centos7 sh]$ ./helloworld.sh
Helloworld

执行脚本 绝对路径

shell
[root@centos7 sh]$ /home/atguigu/shells/helloworld.sh
Helloworld

注意:

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

【了解】第三种:在脚本的路径前加上“.”或者 source

有以下脚本

shell
[root@centos7 sh]$ cat test.sh
#!/bin/bash
A=5
echo $A

分别使用 sh,bash,./ 和 . 的方式来执行,结果如下:

shell
[root@centos7 sh]$ bash test.sh
[root@centos7 sh]$ echo $A
[root@centos7 sh]$ sh test.sh
[root@centos7 sh]$ echo $A
[root@centos7 sh]$ ./test.sh
[root@centos7 sh]$ echo $A
[root@centos7 sh]$ . test.sh
[root@centos7 sh]$ echo $A
5

原因:

前两种方式都是在当前 shell 中打开一个子 shell 来执行脚本内容,当脚本内容结束,则 子 shell 关闭,回到父 shell 中。 第三种,也就是使用在脚本路径前加“.”或者 source 的方式,可以使脚本内容在当前 shell 里执行,而无需打开子 shell!这也是为什么我们每次要修改完/etc/profile 文件以后,需 要 source 一下的原因。

开子 shell 与不开子 shell 的区别就在于,环境变量的继承关系,如在子 shell 中设置的 当前变量,父 shell 是不可见的