在 Linux 中调用其他 .sh 文件的最佳实践
在 Linux 中,您可以使用以下几种方法在一个 .sh 文件中调用其他 .sh 文件:
- 使用 source 命令:
source /path/to/other.sh
或简写为:
. /path/to/other.sh
这种方式会将其他 .sh 文件中的代码直接嵌入到当前 .sh 文件中,并可以共享变量。
- 使用 ./ 来执行其他 .sh 文件:
./other.sh
这种方式会通过创建一个新的子 shell 来执行其他 .sh 文件,但变量不能在父 shell 中共享。
- 使用 bash 命令来执行其他 .sh 文件:
bash /path/to/other.sh
这种方式会启动一个新的 bash shell 来执行其他 .sh 文件,同样变量不能在父 shell 中共享。
以下是一个示例:
main.sh 文件:
#!/bin/bash
# 调用其他 .sh 文件
source /path/to/other.sh
# 执行其他的 .sh 文件
./another.sh
# 使用 bash 命令执行其他的 .sh 文件
bash /path/to/another.sh
# 执行其他的 .sh 文件,并传递参数
./script.sh arg1 arg2
other.sh 文件:
#!/bin/bash
# 在这里编写 other.sh 文件的代码
echo '执行了 other.sh 文件'
another.sh 文件:
#!/bin/bash
# 在这里编写 another.sh 文件的代码
echo '执行了 another.sh 文件'
script.sh 文件:
#!/bin/bash
# 在这里编写 script.sh 文件的代码
echo '执行了 script.sh 文件'
echo '参数 1: $1'
echo '参数 2: $2'
在终端中,执行 main.sh 文件:
bash main.sh
输出结果:
执行了 other.sh 文件
执行了 another.sh 文件
执行了 another.sh 文件
执行了 script.sh 文件
参数 1: arg1
参数 2: arg2
请注意,确保在调用其他 .sh 文件之前,给文件设置执行权限:
chmod +x /path/to/other.sh
chmod +x /path/to/another.sh
chmod +x /path/to/script.sh
总结:
- source 命令适合于共享变量和代码。
- ./ 和 bash 命令适合于执行独立的脚本。
- 确保在调用其他 .sh 文件之前设置执行权限。
原文地址: https://www.cveoy.top/t/topic/pmzH 著作权归作者所有。请勿转载和采集!