运行 Shell 脚本有两种方法,一种在新进程中运行,一种是在当前 Shell 进程中运行
在新进程中运行 Shell 脚本
在新进程中运行 Shell 脚本有多种方法。
1) 将 Shell 脚本作为程序运行
Shell 脚本也是一种解释执行的程序,可以在终端直接调用(需要使用 chmod 命令给 Shell 脚本加上执行权限)
# 通过这种方式运行脚本,脚本文件第一行的#!/bin/bash一定要写对,好让系统查找到正确的解释器
"""
[root@server1 mnt]# ls
test.sh
[root@server1 mnt]# chmod +x test.sh
[root@server1 mnt]# ./test.sh
What is your name?
dd
Hello, dd
chmod +x表示给 test.sh 增加执行权限
"""
shell 脚本作为参数传递给 Bash 解释器
"""
你也可以直接运行 Bash 解释器,将脚本文件的名字作为参数传递给 Bash,如下所示:
What is your name?
dd
Hello, dd
通过这种方式运行脚本,不需要在脚本文件的第一行指定解释器信息,写了也没用
[root@server1 mnt]# /bin/sh test.sh
What is your name?
dd
Hello, dd
[root@server1 mnt]# which /bin/bash
/bin/bash
[root@server1 mnt]# bash test.sh
What is your name?
dd
Hello, dd
[root@server1 mnt]# which bash
/usr/bin/bash
"""
检测是否开启了新进程
Linux 中的每一个进程都有一个唯一的 ID,称为 PID,使用$$变量就可以获取当前进程的 PID
[root@server1 ~]# cd /mnt/
[root@server1 mnt]# ls
test.sh
[root@server1 mnt]# vim check.sh
[root@server1 mnt]# echo $$
1572 #当前进程的PID
[root@server1 mnt]# chmod +x check.sh
[root@server1 mnt]# ./check.sh
1576 #新进程的PID
[root@server1 mnt]# echo $$
1572 #当前进程的PID
[root@server1 mnt]# /bin/bash check.sh
1577 #新进程的PID
[root@server1 mnt]# cat check.sh
#!/bin/bash
echo $$ #输出当前进程PID
## 进程的 PID 都不一样,当然就是两个进程了。
在当前进程中运行 Shell 脚本
这里需要引入一个新的命令——source 命令。source 是 Shell 内置命令的一种,它会读取脚本文件中的代码,并依次执行所有语句。你也可以理解为,source 命令会强制执行脚本文件中的全部命令,而忽略脚本文件的权限
source 命令的用法为:
source filename
也可以简写为:
. filename
两种写法的效果相同。对于第二种写法,注意点号.和文件名中间有一个空格
"""
[root@server1 mnt]# cat test2.sh
echo "What is your name?"
read PERSON
echo "Hello, $PERSON"
[root@server1 mnt]# ls -l
total 12
-rwxr-xr-x 1 root root 44 Dec 12 10:06 check.sh
-rwxr-xr-x 1 root root 60 Dec 12 10:10 test2.sh
-rwxr-xr-x 1 root root 60 Dec 12 09:41 test.sh
[root@server1 mnt]# chmod -x test2.sh
[root@server1 mnt]# ls -l
total 12
-rwxr-xr-x 1 root root 44 Dec 12 10:06 check.sh
-rw-r--r-- 1 root root 60 Dec 12 10:10 test2.sh
-rwxr-xr-x 1 root root 60 Dec 12 09:41 test.sh
[root@server1 mnt]# source test2.sh
What is your name?
dd
Hello, dd
[root@server1 mnt]# . test2.sh
What is your name?
dd
Hello, dd
[root@server1 mnt]# source ./test2.sh
What is your name?
dd
Hello, dd
使用 source 命令不用给脚本增加执行权限,并且写不写./都行很方便
"""
检测是否在当前 Shell 进程中
[root@server1 mnt]#
[root@server1 mnt]# echo $$
1572
[root@server1 mnt]# source ./check.sh
1572
[root@server1 mnt]# echo $$
1572
[root@server1 mnt]# . ./check.sh
1572
shell脚本运行的方式
# 使用source或'.'可以将自身脚本中的变量值或函数等的返回值传递到当前父shell脚本中使用
[root@server1 mnt]# sh 3.sh
[root@server1 mnt]# echo $userdir
[root@server1 mnt]# source 3.sh
[root@server1 mnt]# echo $userdir
/mnt
[root@server1 mnt]# cat 3.sh
userdir=`pwd`
"""
我们可以得出以下结论:
儿子shell脚本会直接继承父亲shell脚本的变量,函数(就好像儿子随父的姓,基因也会继承父亲)等,反之则不可以
如果希望反过来继承(就好像是让父亲随儿子姓,让父亲的基因也继承儿子的),就要用source或'.'在父亲shell脚本中事先加载儿子的shell脚本
"""
因篇幅问题不能全部显示,请点此查看更多更全内容