Linux操作系统——Shell脚本入门
Shell 脚本入门
目录
背景引入
1)脚本格式
脚本以#!/bin/bash 开头(指定解析器)
写成这个也可以#!/bin/sh
2)第一个 Shell 脚本:helloworld.sh
(1)需求:创建一个 Shell 脚本,输出 helloworld
(2)案例实操:
[atguigu@hadoop101 shells]$ touch helloworld.sh
[atguigu@hadoop101 shells]$ vim helloworld.sh
在 helloworld.sh 中输入如下内容
#!/bin/bash
echo "helloworld"
3)脚本的常用执行方式
第一种:采用 bash 或 sh+脚本的相对路径或绝对路径(不用赋予脚本+x 权限)
sh+脚本的相对路径
[atguigu@hadoop101 shells]$ sh ./helloworld.sh
Helloworld
sh+脚本的绝对路径
[atguigu@hadoop101 shells]$ sh /home/atguigu/shells/helloworld.sh
helloworld
bash+脚本的相对路径
[atguigu@hadoop101 shells]$ bash ./helloworld.sh
Helloworld
bash+脚本的绝对路径
[atguigu@hadoop101 shells]$ bash /home/atguigu/shells/helloworld.sh
Helloworld
第一种执行方式,实际上往往不用这种方式
第二种:采用输入脚本的绝对路径或相对路径执行脚本(必须具有可执行权限+x
)
①首先要赋予 helloworld.sh 脚本的+x 权限
[atguigu@hadoop101 shells]$ chmod +x helloworld.sh
②执行脚本
相对路径
[atguigu@hadoop101 shells]$ ./helloworld.sh
Helloworld
绝对路径
[atguigu@hadoop101 shells]$ /home/atguigu/shells/helloworld.sh
Helloworld
第二种方式
注意:
第一种执行方法,本质是 bash 解析器帮你执行脚本,所以脚本本身不需要执行权限。第二种执行方法,本质是脚本需要自己执行,所以需要执行权限。
问题与解答
问题:为什么第一种采用bash或sh+脚本的相对路径或绝对路径的方式不用赋予脚本+x权限,而采用输入脚本的绝对路径或相对路径执行脚本必须具有可执行权限+x呢?
答:
第一种方式是我们单独的又使用了一个bash命令,相当于又起来一个bash进程,然后指定文件名,相当于这是bash命令的参数。是bash的参数传入的
第二种方式是直接调用脚本,让当前的bash、shell环境执行这个脚本。
【了解】第三种:在脚本的路径前加上“.”或者 source
①有以下脚本
[atguigu@hadoop101 shells]$ cat test.sh
#!/bin/bash
A=5
echo $A
②分别使用 sh,bash,./ 和 . 的方式来执行,结果如下:
[atguigu@hadoop101 shells]$ bash test.sh
[atguigu@hadoop101 shells]$ echo $A
[atguigu@hadoop101 shells]$ sh test.sh
[atguigu@hadoop101 shells]$ echo $A
[atguigu@hadoop101 shells]$ ./test.sh
[atguigu@hadoop101 shells]$ echo $A
[atguigu@hadoop101 shells]$ . test.sh
[atguigu@hadoop101 shells]$ echo $A
5
注意:./hello.sh 和 . hello.sh这两种的执行方式是完全不同的,前面./指的是相对路径,而后面的”.”是一个命令,后面的”hello.sh”是这个”.”命令的参数
第三种执行方式和前两种执行方式的区别
原因:
前两种方式都是在当前 shell 中打开一个子 shell 来执行脚本内容,当脚本内容结束,则子 shell 关闭,回到父 shell 中。
第三种,也就是使用在脚本路径前加“.”或者 source 的方式,可以使脚本内容在当前shell 里执行,而无需打开子 shell!这也是为什么我们每次要修改完/etc/profile 文件以后,需要 source 一下的原因。
开子 shell 与不开子 shell 的区别就在于,环境变量的继承关系,如在子 shell 中设置的当前变量,父 shell 是不可见的。
子Shell进程
前面两种本质上都是打开了一个子Shell。
source和“.”命令,根本就不启动子Shell进程,直接在当前的Shell里面,把我们当前的脚本每一行命令拿出来一行一行解析,直接执行。好处:没有父子Shell嵌套的环境了。嵌套环境最大的影响:当前环境变量获取不到,生效的作用范围不一样。更改.profile没有生效怎么办?直接source一下。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/85628.html