壁立千仞 无欲则刚
后缀是.sh不写也是可以运行,但是约定俗成
脚本文本以#!/bin/bash开头(指定解析器)
文本#为注释
(1)需求:创建一个 Shell 脚本,输出 helloworld
(2)案例实操:
[root@centos7-101 ~]# mkdir scripts
[root@centos7-101 scripts]# touch helloworld.sh
[root@centos7-101 scripts]# vim helloworld.sh
在 helloworld.sh 中输入如下内容
#!/bin/bash
echo "helloworld"
(3)脚本的常用执行方式
sh+脚本的相对路径(当前路径./)
[root@centos7-101 scripts]# sh ./helloworld.sh
hello word
sh+脚本的绝对路径
[root@centos7-101 scripts]# sh /root/script/helloworld.sh
hello word
bash+脚本的相对路径
[root@centos7-101 scripts]# bash ./helloworld.sh
hello word
[root@centos7-101 scripts]# bash helloworld.sh
hello word
bash+脚本的绝对路径
[root@centos7-101 scripts]# bash /root/script/helloworld.sh
hello word
①首先要赋予 helloworld.sh 脚本的+x 权限
[root@centos7-101 scripts]# chmod u+x helloworld.sh
②执行脚本
相对路径
[root@centos7-101 scripts]# ./helloworld.sh
hello word
绝对路径
[root@centos7-101 scripts]# /root/script/helloworld.sh
hello word
注意:
第一种执行方法,本质是 bash 解析器帮你执行脚本,所以脚本本身不需要执行权限。
第二种执行方法,本质是脚本需要自己执行,所以需要执行权限。
想要写helloworld.sh直接执行,需要在环境变量中添加helloworld.sh所在的目录。
[root@centos7-101 scripts]# echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
①有以下脚本
[root@centos7-101 scripts]# touch test.sh
[root@centos7-101 scripts]# vim test.sh
[root@centos7-101 scripts]# chmod u+x ./test.sh
[root@centos7-101 scripts]# cat test.sh
#!/bin/bash
# 对环境变量A赋值
A=5
# 取出A值
echo $A
②分别使用 sh,bash,./ 和 . 的方式来执行,结果如下:
bash
[root@centos7-101 scripts]# bash test.sh
5
[root@centos7-101 scripts]# echo $A
sh
[root@centos7-101 scripts]# sh test.sh
5
[root@centos7-101 scripts]# echo $A
./
[root@centos7-101 scripts]# ./test.sh
5
[root@centos7-101 scripts]# echo $A
.
[root@centos7-101 scripts]# . test.sh
5
[root@centos7-101 scripts]# echo $A
5
与前两种区别:
source是bash的内置命令,本身是csh中的,另一种实现是bash的”.“,所以”.“与source效果相同。
bash、sh、./helloworld.sh本质上都是打开了一个子Shell进程,当前的Shell环境不受影响,
“.”或者 source 是不启动子Shell进程的,直接在当前的Shell进程中执行,好处是没有父子环境嵌套,可以设置一些环境变量,如果有父子嵌套,在子Shell设置环境变量,父Shell中是获取不到的。
原因:
前两种方式都是在当前 shell 中打开一个子 shell 来执行脚本内容,当脚本内容结束,则子 shell 关闭,回到父 shell 中。
第三种,也就是使用在脚本路径前加“.”或者 source 的方式,可以使脚本内容在当前shell 里执行,而无需打开子 shell!这也是为什么我们每次要修改完/etc/profile 文件以后,需要 source 一下的原因。
开子 shell 与不开子 shell 的区别就在于,环境变量的继承关系,如在子 shell 中设置的当前变量,父 shell 是不可见的