软硬件环境
- ubuntu 18.04 64bit
- shell
视频看这里
此处是 youtube 的播放链接,需要科学上网。喜欢我的视频,请记得订阅我的频道,打开旁边的小铃铛,点赞并分享,感谢您的支持。
简介
linux 系统中,在一个 shell 脚本中去调用另一个 shell 脚本,这种需求还是蛮常见的,本文就来分享几种实现脚本调用的方法。
首先准备一个被调用的脚本 sub.sh
#!/bin/bash
echo "I am sub shell script."
方法一
使用 source 命令,代码如下,在 main.sh 中调用 sub.sh
#!/bin/bash
echo "I am main shell script."
source sub.sh
执行 main.sh 使用命令
bash main.sh
执行的结果是
(base) xugaoxiang@1070Ti:~/workshop/scripts$ bash main.sh
I am main shell script.
I am sub shell script.
注意到,上面并没有使用 sh main.sh,这是因为在 ubuntu 18.04 中 sh 指向的是 dash
(base) xugaoxiang@1070Ti:~/workshop/scripts$ ls -l /bin/sh
lrwxrwxrwx 1 root root 4 3月 24 15:21 /bin/sh -> dash
如果你想让 sh 指向 bash 的话,也是可以的,通过下面的命令进行修改
sudo dpkg-reconfigure dash

接下来再次确认是否修改成功
(base) xugaoxiang@1070Ti:~/workshop/scripts$ ls -l /bin/sh
lrwxrwxrwx 1 root root 4 8月 25 15:40 /bin/sh -> bash
方法二
使用 . 号,注意点号和被调用脚本之间有个空格
#!/bin/bash
echo "I am main shell script."
. sub.sh
执行结果和方法一是一模一样的
使用shell显示调用
在 main.sh 中使用 bash sub.sh 来调用
#!/bin/bash
echo "I am main shell script."
bash sub.sh
执行的结果也是一样的
备注
上述三种方法中,其中方法一和方法二,本质上是一样的。main.sh 会将 sub.sh 脚本中的内容拷贝过来,由一个 shell 进程来执行。为验证这个,我们简单修改下 sub.sh,让它进入 sleep 100
#!/bin/bash
echo "I am sub shell script."
sleep 100
在 main.sh 中使用 source 或 . 调用时,通过 ps 命令可以看到 main.sh,但是没有 sub.sh 进程

而使用 bash 命令来调用脚本 sub.sh 和前两种方法有着本质的区别。使用 bash 命令会开启新的 shell 进程来执行脚本。
