文章目录
- chmod 赋予权限运行
- sh script.sh
-
- bash script.sh
- source 或 . 脚本
chmod 赋予权限运行
chmod +x script.sh
./script.sh
- 创建新的子进程,不会影响当前 shell 的环境变量。
- #!(Shebang) 指定的解释器(如 #!/bin/bash)决定了脚本执行的 shell 类型,与当前 shell 无关
sh script.sh
- 不会创建新的 shell 进程,而是 调用 /bin/sh 解释器执行。
- 不受 Shebang (#!) 影响,总是由 /bin/sh 执行,即使 script.sh 里 #!/bin/bash 也会忽略。
- 不会影响当前 shell 的环境变量。
适用场景
- 在未知环境下执行脚本(比如不确定目标环境是否安装了 Bash)。
- sh 可能是 dash(Debian/Ubuntu)或 bash(CentOS)等的软链接,语法可能有所不同。
- 如果脚本包含 bash 特有语法(如 [[ 条件判断),可能会报错。
- 运行不需要改变当前 shell 环境的简单脚本。
bash script.sh
- 显式使用 bash 解释器(不管 Shebang 是什么)。
- 创建一个新的 Bash 进程,不会影响当前 shell 环境。
source 或 . 脚本
source script.sh
. script.sh
- 不会创建新进程,而是 在当前 shell 中执行。
- 可以修改当前 shell 的环境变量(如 export PATH)。
- Shebang (#!) 无效,因为脚本的每一行代码都直接在当前 shell 执行。